Python [Errno 13]权限被拒绝: [英] Python [Errno 13] Permission denied:

查看:1194
本文介绍了Python [Errno 13]权限被拒绝:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个快速的python脚本,以遍历当前文件夹中的所有csv文件,并从其中删除标题行,然后将它们存储在单独的文件夹中.

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.

当前工作目录包含四个示例csv文件和python脚本.执行后,脚本将创建HeaderRemoved目录.

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.

此刻我在Windows计算机上.

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

示例输出:

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'

推荐答案

正如Charles Duffy在我的原始问题上评论的那样,问题实际上是,用于读写文件的代码行并未缩进范围之内. for循环.更正缩进可解决此问题,现在可以按需工作.

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.

这篇关于Python [Errno 13]权限被拒绝:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆