Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
802 views
in Technique[技术] by (71.8m points)

csv - 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'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...