[英]Appending to a .csv File in Python
我试图使用Python写入现有的.csv文件,但我不想将数据附加到现有文件的底部,而是将新信息附加到.csv文件的新列。 这样做的原因是我想要“无限地”循环遍历代码的读取数据部分,然后将每次循环迭代期间读取的数据添加到新列而不是行。 从本质上讲,我想要的东西如下:
Row1Iteration1, Row1Iteration2, Row1Iteration3,..., Row1IterationX
Row2Iteration1, Row2Iteration2, Row2Iteration3,..., Row2IterationX
Row3Iteration1, Row3Iteration2, Row3Iteration3,..., Row3IterationX
Row4Iteration1, Row4Iteration2, Row4Iteration3,..., Row4IterationX
Row5Iteration1, Row5Iteration2, Row5Iteration3,..., Row5IterationX
代替:
Row1Iteration1
Row2Iteration1
Row3Iteration1
Row4Iteration1
Row5Iteration1
Row1Iteration2
Row2Iteration2
Row3Iteration2
etc...
有没有人知道这样做的方法还是这是.csv文件的一个不可能的约束? 还有另一种方法,除了.csv,我可以做到这一点,仍然可以用Excel操作?
这在我所知道的任何系统或文件类型上都是不可能的。 您必须读取数据,操作它并保存/覆盖原始文件。 这就是文件I / O几乎适用于任何操作系统的方式。 您可以读取文件,(通过)写入文件并附加到文件末尾,这就是全部。
如果您的文件非常大,您可以逐个阅读,进行操作并将其写入临时文件。 完成后,可以使用新的临时文件替换原始文件。
我希望这个例子可以帮助你:
# of course you should read the file someway
s = """
Row1Iteration1, Row1Iteration2, Row1Iteration3
Row2Iteration1, Row2Iteration2, Row2Iteration3
Row3Iteration1, Row3Iteration2, Row3Iteration3
Row4Iteration1, Row4Iteration2, Row4Iteration3
Row5Iteration1, Row5Iteration2, Row5Iteration3
"""
ncols = 3
iterations = []
for line in s.strip().split('\n'):
iterations.append([l.strip() for l in line.split(',')])
with open('output.csv', 'w') as out:
for col in xrange(ncols):
for it in iterations:
print it[col]
out.write(col)
正如Chinmay所说,你最好的选择是阅读csv文件,按摩它,然后将其输出回csv。 看看这个stackoverflow讨论 ,它似乎可以解决类似于你所问的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.