python程序 - 修改文本文件中的列
我需要在文本文件中删除几个列,其中一个在中间位置,并添加两个新列。以下是我的代码。除了第一行之外,它都能正常工作。我该如何让它对所有行都有效呢?
infile = open('a.txt').read()
list =infile.split( );
print ("Hello " + list[0]+ "world" + list[2] + " " + list[3]+"313")
举个例子,我的原始文件中有5列:
1 2 3 4 5
5 2 2 5 2
1 2 5 6 2
1 2 5 1 2
1 5 6 7 8
输出应该是这样的:
1 "yyy" 4 "xxx"
5 "yyy" 5 "xxx"
1 "yyy" 6 "xxx"
1 "yyy" 1 "xxx"
1 "yyy" 7 "xxx"
3 个回答
-2
使用打开的文件对象上的read()方法,可以一次性读取文件的全部内容,结果会是一个长长的字符串。如果你想把每一行单独存起来,得根据行的分隔符(比如\n、\r、\n\r)来把这个字符串切分开。使用readlines()方法则会把文件的内容按行存储成一个列表。
关于如何更新文件内容的问题,我建议使用readlines()方法和列表推导式,这样可以用很少的代码快速完成。下面的代码示例可以参考。变量row_delimiter和new_content可以根据你的需要进行替换。
#declare paths
path1 = "C:\foo.txt"
path2 = "C:\bar.txt"
#read file and update content
with open(path1, "r") as read:
content = [line.split(row_delimiter) for line in read.readlines()]
[row[index] = new_content for row in content]
read.close()
#write new content
with open(path2, "r") as wrt:
[wrt.write(line) for line in content]
wrt.close()
0
默认情况下,split方法会在空格处进行分割……你可以检查一下你列表的长度。
试着使用readlines()方法,然后对结果进行循环处理,就像你之前做的那样。
0
更新的回答,因为规格有了更新:
对每一行单独使用 split
,然后打印你格式化后的行。如果你只是想打印结果:
with open('a.txt', 'r') as infile:
for line in infile:
line = line.split()
new_line = '{0} "yyy" {1} "xxx"'.format(line[0], line[3])
print(new_line)
如果你想把输出写入一个新的文件 b.txt
(而不是仅仅打印出来):
with open('a.txt', 'r') as infile:
with open('b.txt', 'w') as outfile:
for line in infile:
line = line.split()
new_line = '{0} "yyy" {1} "xxx"\n'.format(line[0], line[3])
outfile.write(new_line)
你示例文件的输出结果:
1 "yyy" 4 "xxx"
5 "yyy" 5 "xxx"
1 "yyy" 6 "xxx"
1 "yyy" 1 "xxx"
1 "yyy" 7 "xxx"