python程序-修改文本文件中的列 我需要删除文本文件中的几个列,其中一个在中间,并添加两个新的。 这是我的密码。它在第一行之外工作。如何使其适用于所有生产线 infile = open('a.txt').read() list =infile.split( ); print ("Hello " + list[0]+ "world" + list[2] + " " + list[3]+"313")

python程序-修改文本文件中的列 我需要删除文本文件中的几个列,其中一个在中间,并添加两个新的。 这是我的密码。它在第一行之外工作。如何使其适用于所有生产线 infile = open('a.txt').read() list =infile.split( ); print ("Hello " + list[0]+ "world" + list[2] + " " + list[3]+"313"),python,file,text,Python,File,Text,例如,我的原始文件中有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" 更新的答案由于更新的规范: 分别对每行应用split,然后打印格式化行。如果您只想打印结

例如,我的原始文件中有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" 

更新的答案由于更新的规范:

分别对每行应用
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
(而不仅仅是打印):

示例文件的输出:

1 "yyy" 4 "xxx"
5 "yyy" 5 "xxx"
1 "yyy" 6 "xxx"
1 "yyy" 1 "xxx"
1 "yyy" 7 "xxx" 

默认情况下拆分在空白处拆分。。。您可以检查列表的长度

尝试执行readlines()并重复执行您已执行的操作。

在打开的文件对象上使用read()方法将文件的整个内容作为一个字符串读取。因此,要将每一行存储为一个列表,必须根据行分隔符(\n\r\n\r)拆分字符串。使用readlines()方法将文件内容作为列表对象逐行存储

为了回答您关于更新文件内容的问题,我将使用readlines()方法和list comprehension快速完成这项工作,只需几行代码。请参见下面的代码示例。变量行分隔符和新内容可以替换为您需要的任何内容

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

不要将
list
用作变量名。你在跟踪内置列表,这绝不是一个好主意。你不需要
并始终使用
在文件自动关闭时打开文件
infle.readlines()
将把内容放入一个列表中,然后在列表上迭代。@user3832446没有想到什么?但是我仍然有可能修改你的代码,使我自己的文件有更多的行和列。。我不知道为什么…@user3832446当然,如果您想要与您要求的不同的东西,您必须修改代码…好的-我发现了问题,文件中有一个空行。谢谢你能再帮我一件事吗?如何删除文件中所有不以“t”开头的行?1。列表理解中的赋值将抛出语法错误。2.使用打开文件时,不需要手动关闭文件。3.如果要写入文件,必须使用
'w'
'r+'
打开它,而不是
'r'
。4.仅仅为了副作用而使用列表理解是一种可怕的做法。
#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()