我用过这个:
f=open('mark.txt','r')
print f.read()
输出:
Name;age;year
Mark;19;3rd Year
如何使用python替换上面的内容,以便输出为:
Name Age Year
Mark 19 3rd Year
我在这个网站上找到了以下代码但是如何运行输出?出来的输出只是空白。
f1=open('mark.txt','r')
f2=open('mark.txt.tmp','w')
for line in f1:
f2.write(line.replace(';','\t'))
f1.close()
f2.close()
答案 0 :(得分:3)
我认为处理数据文件的最佳方法是使用csv module。
import csv
with open('mark.txt', 'rb') as data_file, open('output.txt', 'wb') as out_file:
reader = csv.reader(data_file, delimiter=';')
writer = csv.writer(out_file, delimiter='\t')
writer.writerows(list(reader))
;
替换为\t
:import csv
import shutil
with open('mark.txt', 'rb') as data_file, open('mark.txt.tmp', 'rb') as out_file:
reader = csv.reader(data_file, delimiter=';')
writer = csv.writer(out_file, delimiter='\t')
writer.writerows(list(reader))
shutil.move('mark.txt.tmp', 'mark.txt')
;
替换为\t
:import csv
with open('mark.txt', 'rb') as data_file:
reader = csv.reader(data_file, delimiter=';')
for row in reader:
print '\t'.join(row)
#print('\t'.join(row)) in Python 3
答案 1 :(得分:1)
with open('mark.txt') as in_file, open('mark.txt.tmp', 'w') as out_file:
for line in in_file:
out_file.write('\t'.join(line.split(';')))
答案 2 :(得分:0)
你可以这样做,
f=open('mark.txt','r')
for line in f.read():
print line.replace(';', '\t')
f.close()