首页 > 解决方案 > csv.writer 没有将整个列表写入从中读取的文件

问题描述

当将 CSV 读入列表然后尝试通过一些修改直接写回同一个 CSV 时,我发现脚本每次都会在完全相同的点过早地跳到下一个文件。

将输出文件更改为辅助文件(.e. filea.csvis read and write is fileaCorrected.csv)有效。

import time
import datetime
import csv
import sys
import glob
import pdb

pattern1 = '%m/%d/%Y %H:%M'
pattern2 = '%m/%d/%Y %H:%M:%S'
pattern3 = '%Y-%m-%d %H:%M:%S'

folderLocation = input("which Folder should be scanned and trimmed EX C:\program files\data:")
endDate = input("what is the last timestamp that should be in the file(s): ")

trimDate = int(time.mktime(time.strptime(endDate, pattern1)))

fileList = sorted(glob.glob(folderLocation+'/*.csv'))

for FileName in fileList:

    removedLines = 0
    FilesComplete = 0
    f = open(FileName)
    csv_f = csv.reader(f)
    #pdb.set_trace()
    header = next(f)
    newFileName = (FileName[:-4]) + " endateremoved.csv"
    with open(FileName, 'w') as csvfile:
        filewriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
        csvfile.write(header)
        for row in csv_f:
            #(FileName," -- ",row[0])
            date_time = row[0]
            epoch = int(time.mktime(time.strptime(date_time, pattern3)))
            if epoch < trimDate:
                lineWriter = ""
                for item in row[:-1]:
                    lineWriter += item + ","
                lineWriter += row[-1]
                #print(lineWriter)
                csvfile.write(lineWriter + "\n")
            else:
                #print("removed line %s" % row)
                removedLines += 1
                break
    FilesComplete += 1
    print (str(FilesComplete) + " Files Completed")
    print("%d files had removed lines" % removedLines)'

我觉得好像我在导致文件过早结束的脚本中犯了一个小错误。

示例输入

car,a
boat,b
plane,c

输出

car,a
boat,b
pla

我可以创建一个解决方法来删除旧文件并重命名新文件,但这似乎很麻烦?对此的任何想法表示赞赏。

标签: pythonlistcsv

解决方案


推荐阅读