我目前有一个逗号分隔的文件,一切都在一行上。我想通过python阅读它并创建一个新行,它看到一个逗号。我将在每一行上执行一些操作,然后我想将每一行导出到一个文件。我真的很感激一些帮助。
答案 0 :(得分:2)
使用split
字符串方法。
'a,b,c,b'.split(',') -> ['a', 'b', 'c', 'b']
因此您可以使用它来处理和写入文件
for row in data.split(','):
file.write(row + '\n')
答案 1 :(得分:1)
您可以将所有行拆分为列表
with open("infile") as f:
lines = f.read().split(",")
with open("outfile.txt", "w") as f1:
for line in lines:
f1.write(line+"\n")
答案 2 :(得分:1)
示例file
:
this,is a,comma,separated,line
示例代码:
with open('file', 'r') as f:
f = f.read().strip('\n').split(',') # strip will get rid of \n at end of the line
with open('outfile', 'w') as o:
for line in f:
# do something with the line here
o.write(line + '\n')
示例outfile
:
this
is a
comma
separated
line