您好,我正在尝试将文件位置表示为变量,因为最终脚本将在另一台机器上运行。这是我尝试过的代码,然后是我得到的错误。在我看来,python 是如何添加“\”的,这就是导致问题的原因。如果是这种情况,我如何才能不插入“\”?谢谢
F = 'C:\Documents and Settings\myfile.txt','r'
f = open(F)
错误
TypeError: invalid file: ('C:\\Documents and Settings\\myfile.txt', 'r')
最佳答案
来自文档:
试试这个:
F = r'C:\Documents and Settings\myfile.txt'
f = open(F, 'r')
关于“双反斜杠”——您需要在字符串中转义反斜杠或使用 r'string'
,请参见:
例如试试这个:
>>> a = 'a\nb'
>>> print a
a
b
要获得您期望的结果,您需要:
>>> a = r'a\nb'
>>> print a
a\nb
或者这个:
>>> a = 'a\\nb'
>>> print a
a\nb
关于file - 类型错误 : invalid file: When trying to make a file name a variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9542043/