这是python编程的基础吗?

时间:2014-01-09 18:05:54

标签: python

我用过这个:

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()

3 个答案:

答案 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()