簡體   English   中英

Python中的文件I / O

[英]File I/O in Python

我正在嘗試讀取CSV文件,然后將讀取的CSV寫入另一個CSV文件。

到目前為止,這是我的代碼:

import csv 
with open ("mastertable.csv") as file:
    for row in file:
    print row  
with open("table.csv", "w") as f:
   f.write(file)

我最終想讀取一個CSV文件,並將其寫入具有附加數據的新CSV中。

嘗試運行該錯誤時,出現此錯誤。

Traceback (most recent call last):
File "readlines.py", line 8, in <module>
f.write(file)
TypeError: expected a character buffer object

從我的了解看來,我必須關閉文件,但是我認為自動關閉了嗎?

我不確定為什么可以在文本中寫一個字符串,但是我不能簡單地將CSV寫到另一個CSV中,就像通過迭代遍歷副本一樣。

要讀取CSV並寫入其他CSV文件,您可以執行以下操作:

with open("table.csv", "w") as f:
    with open ("mastertable.csv") as file:
        for row in file:
           f.write(row)

但是,只有在轉錄時需要編輯行時,我才會這樣做。 對於所描述的用例,您可以簡單地用手先將其復制,然后再打開以附加到其中。 此方法將更快,更不用說更易讀了。

with運算符將為您處理文件關閉,並在您離開該代碼塊時關閉文件(由縮進級別提供)

看來您打算使用Python csv模塊。 以下是您要達到的目標的良好起點:

import csv 

with open("mastertable.csv", "r") as file_input, open("table.csv", "wb") as file_output:
    csv_input = csv.reader(file_input)
    csv_output = csv.writer(file_output)

    for cols in csv_input:
        cols.append("more data")
        csv_output.writerow(cols)

這將一次讀取mastertable.csv文件作為列列表。 我追加了一個額外的列,然后將每一行寫入table.csv

注意,當您離開with語句的范圍時,該文件將自動關閉。

file變量不是真正的實際文件數據,而是用於讀取數據的引用指針。 當您執行以下操作時:

with open ("mastertable.csv") as file: for row in file: print row

文件指針自動關閉。 write方法期望將字符緩沖區或字符串作為輸入而不是文件指針。

如果只想復制數據,則可以執行以下操作:

 data = ""
 with open ("mastertable.csv","r") as file:
     data = file.read()
 with open ("table.csv","a") as file:
     file.write(data)`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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