使用 Python 在 csv 文件中的特定列上写入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16695740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:23:38 来源:igfitidea点击:
Use Python to write on specific columns in csv file
提问by Laith
I have data in a file and I need to write it to CSV file in specific column. The data in file is like this:
我在文件中有数据,我需要将其写入特定列中的 CSV 文件。文件中的数据是这样的:
002100
002077
002147
My code is this:
我的代码是这样的:
import csv
f = open ("file.txt","r")
with open("watout.csv", "w") as output:
for line in f :
c.writerows(line)
It is always writes on the first column. How could I resolve this? Thanks.
它总是写在第一列上。我怎么能解决这个问题?谢谢。
采纳答案by Laith
This is how I solved the problem
这就是我解决问题的方法
f1 = open ("inFile","r") # open input file for reading
with open('out.csv', 'wb') as f: # output csv file
writer = csv.writer(f)
with open('in.csv','r') as csvfile: # input csv file
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
row[7] = f1.readline() # edit the 8th column
writer.writerow(row)
f1.close()

