当我尝试执行下面的文件写入时,我得到了一个错误,如下所示。。。我做错了什么?
# create a method that writes to a file.
f = open("C:UsersQamarAliDocumentsafaq's stuffmyFile.txt", "r+")
f.write('0123456789abcdef')
错误如下:
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
IOError: [Errno 22] invalid mode ('r+') or filename: "C:\Users\QamarAli\Documentsx07faq's stuff\myFile.txt"
>>>
尝试使用os.path
和os.sep
在windows上构造文件路径:
import os
file_path = os.path.join("C:" + os.sep, "Users", "QamarAli", "Documents", "afaq's stuff", "myFile.txt")
print file_path
print os.path.exists(file_path)
a
是一个转义序列(看看文件名中它发生了什么(。使用Windows路径时使用原始字符串来告诉Python不要解释反斜杠转义序列:
r"C:UsersQamarAliDocumentsafaq's stuffmyFile.txt"
^ add this thing
在路径中使用正斜杠。
f = open("C:/Users/QamarAli/Documents/afaq's stuff/myFile.txt", "r+")
f.write('0123456789abcdef')
f = open("C:UsersQamarAliDocumentsafaq's stuffmyFile.txt", "a+")
f.write('0123456789abcdef')
相反,试试这个:
import os
f = open(os.path.join("C:\", "Users", "QamarAli", "Documents", "afaq's stuff", "myFile.txt"), "r+")
f.write('0123456789abcdef')
f.close()
请确保该文件已经存在,并且路径有效。
我现在也看到了这一点,看起来你可能使用了错误的路径,看看ineterpreter给你的错误。它不是afaq's stuff
,而是说x07faq's stuff
加上它是我唯一看到一个斜杠的地方。我想我同意blender的观点,你们的文件路径不对。