我有一個輸入文件,其中我正在進行字符串替換操作。替換後無法寫入CSV
我按單元格讀取文件單元格,替換字符串,然後將其寫回新的CSV文件。
input_file = open('/Users/tcssig/Desktop/unstacked2.csv', 'r', encoding='utf-8')
output_file = open('/Users/tcssig/Desktop/unstacked3.csv', 'w', encoding='utf-8')
writer = csv.writer(output_file , delimiter=' ')
reader = csv.reader(input_file)
for row in reader:
for string in row:
data = [string.replace('read','write')]
print(data)
writer.writerow(data)
上面的代碼運行良好,但我得到一個空的輸出文件。
Example of data :
reading reading reading reading
interval 0 1 2 3
who axis
Mikael X 0 10 20 30
Mikael Y 50 40 30 20
Mikael Z 100 90 80 70
Mike X 0 0.1 0.2 0.3
Mike Y 0.5 0.4 0.3 0.2
麥克Z 1 0.9 0.8 0.7
我在想什麼?
更正壓痕;目前還不清楚哪些代碼落入了「在行中的字符串」塊中。此外,要清楚,你是否試圖將每個單元格轉換爲單獨的行,或者只是替換單元格中的值? – ShadowRanger
考慮使用['with'](https://docs.python.org/2/reference/compound_stmts.html#the-with-statement)語句自動關閉文件。 – martineau
@scott,添加了上面的數據示例 – Sarang