file - 类型错误 : invalid file: When trying to make a file name a variable

标签 file python-3.x

您好,我正在尝试将文件位置表示为变量,因为最终脚本将在另一台机器上运行。这是我尝试过的代码,然后是我得到的错误。在我看来,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/

相关文章:

java - 线程等待直到文件修改

Java:向文件写入/读取字符会产生不同的结果

java - 将文件写入 sdcard

python - 在 python 中迭代和更新列表

python - 如何使用 meza 从 .mdb 获取表?

c# - StreamWriter 不附加到文件,而是在不同的目录中创建一个新文件

C++ 从文件的一行中搜索某些单词,然后在这些单词之后插入一个单词

python - 在Python中将字符串解码为日语字符

python - libpng 警告 : interlace handling should be turned on when using png_read_image in Python/PyGame

python - 实时拦截子进程输出的问题