gpt4 book ai didi

python - 替换后无法写入 CSV

转载 作者:行者123 更新时间:2023-11-30 22:49:41 24 4
gpt4 key购买 nike

我有一个输入文件,我在其中进行字符串替换操作。

我逐个单元读取文件,替换字符串,然后将其写回新的 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

我错过了什么?

最佳答案

关闭您的文件:

output_file.close()
input_file.close()

另请参阅有关使用上下文管理器的答案 https://stackoverflow.com/a/441446/4663466

关于python - 替换后无法写入 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39652537/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com