0

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"
>>> 
1
  • 1
    You could also just use forward slashes. Commented Dec 24, 2012 at 0:35

4 Answers 4

3

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)
Sign up to request clarification or add additional context in comments.

Comments

2

\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

4 Comments

Traceback (most recent call last): File "<interactive input>", line 1, in <module> IOError: [Errno 2] No such file or directory: "C:\\Users\\QamarAli\\Documents\\afaq's stuff\\myFile.txt"
@AfaqQamar: Does that file exist? No spelling errors in your path?
no there is no error issues, i pasted it from file properties.
@AfaqQamar: Does that file exist or are you trying to create it?
0

Use forward slash in path.

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

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.