简体   繁体   中英

Python [Errno 13] Permission denied:

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.

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.

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.

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)

Here's some data frame

# that gave me error no.13 also after installing openpyxl and xlrd
df2.to_excel('foo.xlsx')

# that again gave me unicode error
df2.to_excel('C:\Users\www\Desktop\nmms\foo.xlsx')

# (DOUBLE "\\") FINALLY THAT WORKED
df2.to_excel('C:\\Users\\www\\Desktop\\nmms\\foo.xlsx')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM