【问题标题】:Why is my created file blank?为什么我创建的文件是空白的?
【发布时间】:2018-01-19 16:51:32
【问题描述】:

我无法将减去标题的数据存储到新文件中。我对 Python 的了解还不够,无法调试。

最终,我想从每个文件中提取数据并存储到一个主 csv 文件中,而不是单独打开每个文件,同时将所有内容复制并粘贴到我想要的主 csv 文件中。

我的代码如下:

       import csv, os

# os.makedirs() command will create a folder titled in green or in apostrophies
os.makedirs('HeaderRemoved', exist_ok=True)

# Loop through every file in the current working directory.
for csvFilename in os.listdir('directory'):
    if not csvFilename.endswith('.csv'):
        continue #skips non-csv files
    print('Removing header from ' + csvFilename + '...')

    ### Read the CSV file in (skipping first Row)###

csvRows = []
csvFileObj = open(csvFilename)
readerObj = csv.reader(csvFileObj)
for row in readerObj:
    if readerObj.line_num == 1:
        continue # skips first row
    csvRows.append(row)
print (csvRows) #----------->Check to see if it has anything stored in array
csvFileObj.close()

    #Todo: Write out the CSV file
csvFileObj = open(os.path.join('HeaderRemoved', 'directory/mainfile.csv'), 'w',
                  newline='')
csvWriter = csv.writer(csvFileObj)
for row in csvRows:
    csvWriter.writerow(row)
csvFileObj.close()

正在“扫描”或“读取”的 csv 文件包含文本和数字。我不知道这是否会阻止脚本正确“读取”并将数据存储到 csvRow 数组中。

【问题讨论】:

    标签: python python-3.x csv


    【解决方案1】:

    问题来自您在循环文件名时重用相同的变量。请参阅listdir 的文档,它返回文件名列表。然后你的 newfile 不再真正指向文件了,但是 到目录中的字符串文件名。 https://docs.python.org/3/library/os.html#os.listdir

    with open(scancsvFile, 'w') as newfile:
        array = []
        #for row in scancsvFile
        for newfile in os.listdir('directory'): # <---- you're reassigning the variable newfile here
            if newfile.line_num == 1:
                continue
            array.append(lines)
    newfile.close()
    

    【讨论】:

      猜你喜欢
      • 2016-04-13
      • 2015-08-18
      • 1970-01-01
      • 2021-07-25
      • 2017-07-06
      • 2011-02-12
      • 1970-01-01
      • 2012-12-08
      • 2017-03-04
      相关资源
      最近更新 更多