我有一个文本文件price.txt
,其中包含以下行:
open
high
low
close
我需要为文本文件中的每一行创建一个单独的csv文件,并将csv文件命名为price1.csv
,price2.csv
,依此类推
我尝试了以下代码
with open('price.txt') as infile, open('outfile.csv','w') as outfile:
for line in infile:
outfile.write(line.replace(' ',','))
我只得到一个包含以下行的csv文件
open
high
low
close
如何为每一行创建一个csv文件?
答案 0 :(得分:0)
这里的代码为每行(带有替换空格-您在示例中放入的逗号)获取带有注释的名为price1.csv
,price2.csv
等的其他文件:
### start a counter for the filename number
i = 0
with open('price.txt') as infile:
### open a loop over rows of input file
for line in infile :
### add 1 to counter
i += 1
### create the output filename for the row
newfile_name = "price" + str(i) + ".csv"
### write in the new filename the modified row
with open(newfile_name,'w') as outfile:
outfile.write(line.replace(' ',','))