我正在尝试编写一个快速的 python 脚本来遍历当前文件夹中的所有 csv 文件并从中删除标题行,然后将它们存储在一个单独的文件夹中。
当前工作目录有四个示例 csv 文件和 python 脚本。执行后,脚本会创建 HeaderRemoved 目录。
似乎在创建文件夹后,尝试读取文件的代码正在尝试访问该文件夹,但查看代码我不确定为什么会这样。
我现在使用的是 Windows 机器。
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()
示例输出:
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'
最佳答案
在我的例子中,我通过 Excel 打开了 csv 文件并运行了脚本。然后发生此 Permission denied 异常。
刚刚关闭打开的文件并再次运行脚本:)
关于Python [Errno 13] 权限被拒绝 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40984791/