This question already has answers here:
PermissionError: [Errno 13] Permission denied
(16 answers)
Closed 6 months ago.
Just starting to learn some Python and I'm having an issue as stated below:
a_file = open('E:\Python Win7-64-AMD 3.3\Test', encoding='utf-8')
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
a_file = open('E:\Python Win7-64-AMD 3.3\Test', encoding='utf-8')
PermissionError: [Errno 13] Permission denied: 'E:\\Python Win7-64-AMD 3.3\\Test\
Seems to be a file permission error, if any one can shine some light it would be greatly appreciated.
NOTE: not sure how Python and Windows files work but I'm logged in to Windows as Admin and the folder has admin permissions.
I have tried changing .exe properties to run as Admin.
When doing;
a_file = open('E:\Python Win7-64-AMD 3.3\Test', encoding='utf-8')
...you're trying to open a directory as a file, which may (and on most non UNIX file systems will) fail.
Your other example though;
a_file = open('E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')
should work well if you just have the permission on a.txt. You may want to use a raw (r-prefixed) string though, to make sure your path does not contain any escape characters like \n that will be translated to special characters.
a_file = open(r'E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')
For me, I was writing to a file that is opened in Excel.
For me, I got this error when I was trying to write a file to a folder and wanted to make sure the folder existed. I accidentally used:
path = Path("path/to/my/file.txt")
path.mkdir(parents=True, exist_ok=True)
with open(path, "w") as file:
...
but the second line means "make a directory at this exact path (and make its parents too, without throwing errors for them existing already)". The third line then throws a PermissionError, because you can't use open() on a directory path, of course! The second line should have been:
path.parent.mkdir(parents=True, exist_ok=True)
I encountered this problem when I accidentally tried running my python module through the command prompt while my working directory was C:\Windows\System32 instead of the usual directory from which I run my python module
Related
I used a online compiler to access a document in my Desktop using python.
file = open(r"C:\Users\SUN\Desktop\oops in python.txt")
for i in file:
print(i)
file.close()
While, I run this code, I am getting this error
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\SUN\\Desktop\\oops in python.txt'
I Checked the file name and the directory. It's all correct. And I continue to get the same error.
Why am I getting this error?
When I run this code in a Offline Compiler, It works. And I Got the output as required.
It's because the online compiler can't access you system files. The website your are using creates a session for you and runs your code on their servers so you can only access the files you created and saved unto their server during your session.
I think the correct filename is "loops in python.txt" and not "oops in python.txt".
Aren't you missing the l in the beginning?
On windows, you can also use forward slashes (/).
with open ensures the file is closed automatically. i.e.:
with open("C:/Users/SUN/Desktop/loops in python.txt") as f:
for l in f:
...
I am trying to loop through 22 .txt files in a directory, read each lines from the file, and apply some conditions, before writing the modified lines in a newly created file in a different folder.
The issue is that the first 12 files are successfully created, but then I get a permission denied error for all subsequent files. The permissions for the files that fail are the exact same ones as the one that succeed.
Here is a simplified version of my code, excluding a bunch of if conditions for simplicity:
files = os.listdir('./folder/')
for file in files:
with open('./folder/' + file, "r") as input:
with open('./folder/mod/' + file[:-4] + '_mod.txt', "w") as output:
lines = input.readlines()
for i in range(len(lines)):
if lines[i][-7:-1] != ' },':
output.write('\n' + lines[i][:-4].replace('"',''))
output.close()
input.close()
I have tried to exclude the first 12 files completely from the source folder, and then not a single file gets written. As if the issue really lies with the .txt files themselves. These files were all generated at the same time, and are fairly simple, so I can't pinpoint any difference between them.
Here is the Stack Trace returned:
Traceback (most recent call last):
File "C:\Users\myname\Documents\project1\main.py", line 8, in <module>
with open('./folder/' + file, "r") as input:
IOError: [Errno 13] Permission denied: './folder/mod'
***EDIT
If I leave only 1 file that was successfully read and written in the source folder, the operation is successful but I still get the same permission denied error.
The stack trace says the problem is that:
`with open('./folder/' + file, "r") as input:`
is trying to open and read "folder/mod/"
os.listdir() will create a list of everything in a folder, including directories.
So since you can't "read" a directory, python is giving you a permission error.
Adding a test to see if the "file" in the for loop is actually a file should solve the problem:
I'm attempting to write a quick python script to iterate through all csv files in the current folder and remove the header row from them then store them in a separate folder.
The current working directory has four sample csv files and the python script. Once executed the script creates the HeaderRemoved directory.
It appears that once the folder is created the code that is attempting to read the files is trying to access the folder but looking at the code I'm not sure why it would be.
I'm on a windows machine at the moment.
import csv, os, argparse, string
from ctypes import *
os.makedirs('HeaderRemoved', exist_ok=True)
# Loop through files in the current working directory
for csvFile in os.listdir('.'):
if not csvFile.endswith('.csv'):
continue # Skips non-csv files
print ('Removing header from ' + csvFile + '...')
# Read in CSV skipping the first row
csvRows = []
csvFileObj = open(csvFile)
csvReader = csv.reader(csvFileObj)
for row in csvReader:
if csvReader.line_num == 1:
continue # Skips the first row
csvRows.append(row)
csvFileObj.close()
# Write out the CSV file
csvFileObj = open (os.path.join('HeaderRemoved', csvFile), 'w', newline='')
for row in csvRows:
csvWriter.writerow(row)
csvFileObj.close()
Sample output:
Removing header from examplefile_1.csv...
Removing header from examplefile_2.csv...
Removing header from examplefile_3.csv...
Removing header from examplefile_4.csv...
Traceback (most recent call last): File "atbs_csv_parse.py", line 14, in <module>
csvFileObj = open(csvFile) PermissionError: [Errno 13] Permission denied: 'HeaderRemoved'
In my case, I had opened the csv file via Excel and ran the script. Then this Permission denied exception occurred.
Just closed the opened file and run the script again :)
In my case, the same error was because I was passing a directory name instead the file name.
Maybe could be the same problem of others.
The file in the script is opened somewhere in the system. That is the reason for getting "PermissionError : [Error 13]".
Solution:
Just close the file and run the script. You won't get the error.
As Charles Duffy commented under my original question, the issue was in fact that the lines of code for reading and writing the files had not been indented to fall within the for loop. Correcting the indentation fixed the issue and it now works as desired.
A good reminder to always check the simple things.... I got so wrapped up in why it wasn't working that I didn't even notice the lack of indentation.
If you are facing the problem where you can use the csv file with hard coded path but can't use with the windows directory or file path as the pandas or other library do not have the permission to use that object diectly, to so you have to convert it to stirng and use. I faced this issue and this solution worked for me.
from pathlib import Path
cur_dir=Path.cwd()
#cwd = os.getcwd()
csv_path=str(cur_dir)+"\\..\\Dataset\\FuelConsumptionCo2.csv"
df = pd.read_csv(csv_path)
I have this piece of code to create a .json file to store python data. When i run it in my server i get this error:
IOError: [Errno 13] Permission denied: 'juliodantas2015.json' at line with open(output_file, 'wb') as fp:
Python code:
fich_input='juliodantas2015.txt'
output_file= fich_input.strip('.txt')+'.json'
import json
with open(output_file, 'wb') as fp:
json.dump('yes', fp)
In command line i typed chmod 777 *.py but still not working. How can i fix this ?
I had a similar problem. I was attempting to have a file written every time a user visits a website.
The problem ended up being twofold.
1: the permissions were not set correctly
2: I attempted to use
f = open(r"newfile.txt","w+") (Wrong)
After changing the file to 777 (all users can read/write)
chmod 777 /var/www/path/to/file
and changing the path to an absolute path, my problem was solved
f = open(r"/var/www/path/to/file/newfile.txt","w+") (Right)
IOError: [Errno 13] Permission denied: 'juliodantas2015.json'
tells you everything you need to know: though you successfully made your python program executable with your chmod, python can't open that juliodantas2015.json' file for writing. You probably don't have the rights to create new files in the folder you're currently in.
I have a really stupid use case for why I got this error. Originally I was printing my data > file.txt
Then I changed my mind, and decided to use open("file.txt", "w") instead. But when I called python, I left > file.txt .....
I faced same issue this morning when I tried to write data to opened excel file note that you can not edit a file when it's open .
Please close the file and then it work normally
I have a CSV file in Documents , and I want to open it with python2.
I run this
print os.getcwd()
/Users/baicai
My file in /Users/baicai/Documents/blabla.csv
I run this get error
df= open('/Documents/blabla.csv')
IOError: [Errno 2] No such file or directory: '/Documents/blala.csv'
or this
f=open('/User/baicai/Documents/blabla.csv')
IOError: [Errno 2] No such file or directory: '/User/baicai/Documents/blabla.csv'
How to read? Thanks
df = open('Documents/blabla.csv') # remove leading /
With the leading /, the operating system thinks you want an absolute path as opposed to a relative path.
or
f=open('/Users/baicai/Documents/blabla.csv') # Users, not User
This one was just a typo :-)