簡體   English   中英

在Python中附加到.csv文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM