从列表写入CSV,write.row似乎停在一个奇怪的地方
我正在尝试合并多个CSV文件。我的初始功能旨在:
- 在目录中查找并计算其中的文件数(假设所有文件均为.csv)
- 打开第一个CSV并将每一行添加到列表中
- 剪辑前三行(我不想要一些无用的列标题信息)
- 将这些结果存储在一个我称为“存档”的列表中
- 打开下一个CSV文件并重复(剪切并将它们附加到“存档”中)
- 当我们没有CSV文件时,我想将完整的“存档”写入单独文件夹中的文件。
因此,例如,如果我要从看起来像这样的三个CSV文件开始。
CSV 1
[]
[['Title'],['Date'],['etc']]
[]
[['Spam'],['01/01/2013'],['Spam is the spammiest spam']]
[['Ham'],['01/04/2013'],['ham is ok']]
[['Lamb'],['04/01/2013'],['Welsh like lamb']]
[['Sam'],['01/12/2013'],["Sam doesn't taste as good and the last three"]]
CSV 2
[]
[['Title'],['Date'],['etc']]
[]
[['Dolphin'],['01/01/2013'],['People might get angry if you eat it']]
[['Bear'],['01/04/2013'],['Best of Luck']]
CSV 3
[]
[['Title'],['Date'],['etc']]
[]
[['Spinach'],['04/01/2013'],['Spinach has lots of iron']]
[['Melon'],['02/06/2013'],['Not a big fan of melon']]
最后我会回家得到类似…
CSV输出
[['Spam'],['01/01/2013'],['Spam is the spammiest spam']]
[['Ham'],['01/04/2013'],['ham is ok']]
[['Lamb'],['04/01/2013'],['Welsh like lamb']]
[['Sam'],['01/12/2013'],["Sam doesn't taste as good and the last three"]]
[['Dolphin'],['01/01/2013'],['People might get angry if you eat it']]
[['Bear'],['01/04/2013'],['Best of Luck']]
[['Spinach'],['04/01/2013'],['Spinach has lots of iron']]
[['Melon'],['02/06/2013'],['Not a big fan of melon']]
所以…我开始写这个:
import os
import csv
path = './Path/further/into/file/structure'
directory_list = os.listdir(path)
directory_list.sort()
archive = []
for file_name in directory_list:
temp_storage = []
path_to = path + '/' + file_name
file_data = open(path_to, 'r')
file_CSV = csv.reader(file_data)
for row in file_CSV:
temp_storage.append(row)
for row in temp_storage[3:-1]:
archive.append(row)
archive_file = open("./Path/elsewhere/in/file/structure/archive.csv", 'wb')
wr = csv.writer(archive_file)
for row in range(len(archive)):
lastrow = row
wr.writerow(archive[row])
print row
这似乎可行…除了当我检查输出文件时,它似乎已停止在结尾处的一个奇怪的位置进行写操作。”
例如:
[['Spam'],['01/01/2013'],['Spam is the spammiest spam']]
[['Ham'],['01/04/2013'],['ham is ok']]
[['Lamb'],['04/01/2013'],['Welsh like lamb']]
[['Sam'],['01/12/2013'],['Sam doesn't taste as good and the last three']]
[['Dolphin],['01/01/2013'],['People might get angry if you eat it']]
[['Bear'],['01/04/2013'],['Best of Luck']]
[['Spinach'],['04/0
真的很奇怪,我无法解决出了什么问题。看起来写得不错,但已决定甚至停止列表条目的一半。追溯一下,我可以确定这与我上次写的“ for
loop”有关,但是我对csv方法不太熟悉。通读了文档,仍然很困惑。
谁能指出我出了问题的地方,如何解决这个问题,以及是否有更好的方法解决所有这些问题!
非常感谢-哇
-
在脚本结束之前,关闭文件句柄。关闭文件句柄还将刷新所有等待写入的字符串。如果您不刷新并且脚本结束,则可能永远不会写入某些输出。
使用
with open(...) as f
语法很有用,因为当Python离开with
-suite时它将为您关闭文件。使用with
,您将永远不会忽略再次关闭文件。with open("./Path/elsewhere/in/file/structure/archive.csv", 'wb') as archive_file: wr = csv.writer(archive_file) for row in archive: wr.writerow(row) print row