当我尝试在下面执行写入文件时,我收到错误,如下所示......我做错了什么?
# create a method that writes to a file.
f = open("C:\Users\QamarAli\Documents\afaq's stuff\myFile.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\\Documents\x07faq's stuff\\myFile.txt"
>>>
答案 0 :(得分:3)
尝试使用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)
答案 1 :(得分:2)
\a
是一个转义序列(看看你的文件名中发生了什么)。使用Windows路径时使用raw strings告诉Python不要解释反斜杠转义序列:
r"C:\Users\QamarAli\Documents\afaq's stuff\myFile.txt"
^ add this thing
答案 2 :(得分:0)
f = open("C:\Users\QamarAli\Documents\afaq's stuff\myFile.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
加上它是我看到单一斜线的唯一地方。我认为我同意搅拌机你提出的路径不对。
答案 3 :(得分:0)
在路径中使用正斜杠。
f = open("C:/Users/QamarAli/Documents/afaq's stuff/myFile.txt", "r+")
f.write('0123456789abcdef')