hamedb71
hamedb71

Reputation: 151

Python: PermissionError while writing a file to windows dir

When i want to open a file in C:\ (windows dir.) this error shows up: PermissionError: [Errno 13] Permission denied: 'C:\h.txt'

What should i do?

I know this question has been asked several times but i can't find solution!

code:

f=open ('C:\\h.txt','w')
f.write ('python')
f.close

Upvotes: 1

Views: 6549

Answers (2)

user4179775
user4179775

Reputation:

I am not on win machine, but give this a try, you can manage permissions using these commands Try to open your file using os.fdopen

 import os
 with os.fdopen(os.open('file.txt', os.O_WRONLY | os.O_CREAT, 0600), 'w') as f:
   f.write(...)     

UPDATE

import os
is_accessible = os.access("C:\\temp\\python",os.F_OK) #Check if you have access, this should be a path
if is_accessible == False: #If you don't, create the path
     os.makedirs("C:\\temp\\python")
os.chdir("C:\\temp\\python") # Check now if the path exist 
f = os.open( "p.txt", os.O_RDWR|os.O_CREAT ) #Create the file 
os.write(f, b"This is a test \n")  #Try to write 
os.close(f)

Upvotes: 1

sotapme
sotapme

Reputation: 4903

I'm not on a Windows machine but perhaps you should try and create this file in the directory c:\Temp.

Likewise make sure you've not got Notepad etc with that file open.

Upvotes: 0

Related Questions