python - csv.writer 没有将整个列表写入从中读取的文件
问题描述
当将 CSV 读入列表然后尝试通过一些修改直接写回同一个 CSV 时,我发现脚本每次都会在完全相同的点过早地跳到下一个文件。
将输出文件更改为辅助文件(.e. filea.csv
is 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
我可以创建一个解决方法来删除旧文件并重命名新文件,但这似乎很麻烦?对此的任何想法表示赞赏。
解决方案
推荐阅读
- php - 如何在 Laravel 中修复意外的 '->' (T_OBJECT_OPERATOR)"?
- postgresql - 通过在 postgresql 上声明变量来选择查询
- android - 按下按钮时在 TextView 上显示 LatLng
- asp.net - Angular js:使用 ng-class 过滤数据
- three.js - 为什么在导出为 GLTF 时,blender rigged 动画会变形?
- python - 在列表元素中获取子字符串 Python - Web Scraping
- asp.net - 在模型类中使用数组或列表
- apache-kafka - 使用 Kafka 消费者重试来维护订购保证
- asp.net-core - 外部包中的模型显示在 swagger 文档中
- angular - 材料自动完成:将多个文本输入链接到一个自动完成面板