Python [Errno 13] Permission denied:

戏子无情 提交于 2019-11-28 08:32:50

问题


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'

回答1:


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 :)




回答2:


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.




回答3:


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.




回答4:


The file in 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.



来源:https://stackoverflow.com/questions/40984791/python-errno-13-permission-denied

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!