open()函数在包含特殊字符的文件路径中无法正常运行 [英] The open() functions doesn't behave correctly with filepath containing special characters

查看:357
本文介绍了open()函数在包含特殊字符的文件路径中无法正常运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写以下简单代码:

I'm writing this simple code:

file = input('File to read: ')
fhand = open(file, 'r')

我要打开的文件称为"test.txt",它位于子文件夹中;因此,我在请求的输入中输入的内容是:"DB \ test.txt".

The file I want to open is called 'test.txt', and it is located in a subfolder; what I put into the requested input therefore is: 'DB\test.txt'.

好:它不起作用,返回此错误消息:

Well: it doesn't work, returning this error message:

OSError: [Errno 22]Invalid argument: 'DB\test.txt'.

我在同一目录中有另一个文件,名为"my_file.txt",尝试打开该文件时不会出错.最后,我还有一个名为"new_file.txt"的文件,这个文件也让我遇到相同的错误.

I have another file in the same directory, called 'my_file.txt', and I don't get errors attempting to open it. Lastly I have another file, called 'new_file.txt', and this one also gets me the same error.

对我来说显而易见的是,open()函数读取"\ t"和"\ n",就好像它们是特殊字符一样.在网络上搜索时,我发现没有什么能真正帮助我避免在用户输入字符串中使用特殊字符... 有人可以帮忙吗?

What seems obvious to me is that the open() function reads the "\t" and the "\n" as if they were special characters; searching on the web I found nothing that really could help me avoiding special characters within user input strings... Could anybody help?

谢谢!

推荐答案

使用精确代码的Python 3不会有任何问题(在传递Windows literal 字符串时,通常会遇到此问题, r前缀是必需的.)

you'll have no problems with Python 3 with your exact code (this issue is often encountered when passing windows literal strings where the r prefix is required).

使用python 2,首先您必须用引号将文件名括起来,然后将解释所有特殊字符(\t\n ...).除非您使用我之前提到的原始前缀输入r"DB\test.txt",否则它开始变得很麻烦:)

With python 2, first you'll have to wrap your filename with quotes, then all special chars will be interpreted (\t, \n ...). Unless you input r"DB\test.txt" using this raw prefix I was mentionning earlier but it's beginning to become cumbersome :)

因此,我建议使用raw_input(并且不要输入带引号的文本).或python版本不可知版本,以仅覆盖python 2覆盖不安全的input:

So I'd suggest to use raw_input (and don't input text with quotes). Or python version agnostic version to override the unsafe input for python 2 only:

try:
    input = raw_input
except NameError:
    pass

然后您的代码可以正常工作,并且您摆脱了代码中可能出现的代码注入(作为奖励)(请参阅python 2特定主题:

then your code will work OK and you got rid of possible code injection in your code as a bonus (See python 2 specific topic: Is it ever useful to use Python's input over raw_input?).

这篇关于open()函数在包含特殊字符的文件路径中无法正常运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆