从CSV文件中删除标题

时间:2019-05-13 02:44:07

标签: python-3.x csv

我有一些代码行本应该帮助从所有行中删除标头

我的工作目录中存在CSV文件。

不幸的是,在运行这些代码后,我在第10行出现了错误

什么可能导致此错误?

谢谢。

下面是代码:

import csv,os

os.makedirs('headerRemoved',exist_ok=True)

for csvFilename in os.listdir('.'):

    if not  csvFilename.endswith('.csv'):

        continue     

 print('Removing header from ' + csvFilename + '...')

csvRows=[]

csvFileObj=open(csvFilename)

readerObj=csv.reader(csvFileObj)

for row in readerObj:

    if readObj.line_num==1:

        continue     

csvRows.append(row)

csvFileObj.close()

for csvFilename in os.listdir('.'):

    if not csvFilename.endswith('.csv'):

        continue       

csvFileObj=open(os.path.join('headerRemoved',csvFilename), 'w',newline='')

csvWriter =CSV.writer(csvFileObj)

for row in csvRows:

    csvWriter.writerow(row)


csvFileObj.close()   

我希望获得不带标题的新创建的CSV行,该标题存储在“ headerRemoved”中,但输出如下:

---------------------------------------------------------------------------
PermissionError                           Traceback (most recent call last)

      <ipython-input-36-5b7fd957ccb0> in <module>()

      8 # Read the CSV file(skipping the first row).

      9 csvRows=[]

---> 10 csvFileObj=open(csvFilename)

     11 readerObj=csv.reader(csvFileOb)

     12 for row in readerObj:

PermissionError: [Errno 13] Permission denied: '__pycache__'

1 个答案:

答案 0 :(得分:1)

如果您的缩进如图所示,那么您将循环浏览第一个for循环中的所有文件,然后再继续进行文件处理部分,因此csvFilenameos.listdir('.')的最后结果,是目录__pycache__,并且目录无法像文件一样打开,因此权限错误。要解决此问题,请将后面的代码缩进for循环中,如下所示(并进行一些重构):

import csv,os

os.makedirs('headerRemoved',exist_ok=True)

for csvFilename in os.listdir('.'):
    if not csvFilename.endswith('.csv'):
        continue

    print('Removing header from ' + csvFilename + '...')

    with open(csvFilename,'r',newline='') as infile:
        with open(os.path.join('headerRemoved',csvFilename),'w',newline='') as outfile:
            r = csv.reader(infile)
            w = csv.writer(outfile)
            next(r) # skip first row
            for row in r:
                w.writerow(row)
相关问题