IOError when writing to file in Python

2019-09-05 21:53发布

When I try to execute below for writing to file, I get an error as shown below... What am I doing wrong?

# create a method that writes to a file.

f = open("C:\Users\QamarAli\Documents\afaq's stuff\myFile.txt", "r+")
f.write('0123456789abcdef')

Here is the error:

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"
>>> 

4条回答
Viruses.
2楼-- · 2019-09-05 22:21

\a is an escape sequence (look what happens to it in your filename). Use raw strings when working with Windows paths to tell Python not to interpret backslash escape sequences:

r"C:\Users\QamarAli\Documents\afaq's stuff\myFile.txt"
^ add this thing
查看更多
狗以群分
3楼-- · 2019-09-05 22:27
f = open("C:\Users\QamarAli\Documents\afaq's stuff\myFile.txt", "a+")
f.write('0123456789abcdef')

instead try this:

import os
f = open(os.path.join("C:\\", "Users", "QamarAli", "Documents", "afaq's stuff", "myFile.txt"),  "r+")
f.write('0123456789abcdef')
f.close()

make sure the file already exists, and the path is valid.

Also I saw this right now, it seems you may be using the wrong path, look at the error the ineterpreter gave you. Instead of afaq's stuff it says x07faq's stuff plus it is the only place where I see a single slash. I think I agree with blender that you file path is not right.

查看更多
地球回转人心会变
4楼-- · 2019-09-05 22:30

Use forward slash in path.

f = open("C:/Users/QamarAli/Documents/afaq's stuff/myFile.txt", "r+")
f.write('0123456789abcdef')
查看更多
虎瘦雄心在
5楼-- · 2019-09-05 22:34

Try to use os.path and os.sep to constructs file paths on 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)
查看更多
登录 后发表回答