Skip to content Skip to sidebar Skip to footer

Ioerror When Writing To File In Python

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\Docum

Solution 1:

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
printos.path.exists(file_path)

Solution 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

Solution 3:

Use forward slash in path.

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

Solution 4:

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.

Post a Comment for "Ioerror When Writing To File In Python"