如何在 python 中编辑 txt 文件

How to edit a txt file in python

我有一个包含如下文本文件的文件夹:

3 0.39453125 0.49609375 0.017578125 0.0302734375
1 0.4130859375 0.5029296875 0.0224609375 0.025390625
5 0.8125 0.46875 0.1123046875 0.0849609375
0 0.4677734375 0.5078125 0.0283203125 0.0380859375

第一个数字是class。我怎样才能使文件中只保留属于 class 0 和 1 的行?

所以最后它应该是这样的:

1 0.4130859375 0.5029296875 0.0224609375 0.025390625
0 0.4677734375 0.5078125 0.0283203125 0.0380859375

我试过这个:

for file in os.listdir(folder):
  with open(file,"r+") as f:
      new_file = f.readlines()
      f.seek(0)
      for line in new_file:
          if line.startswith('0') or line.startswith('1'):
              f.write(line)
      f.truncate()

以下代码应仅 return 数组中的第 0 行和第 1 行称为 write。

write = []   
with open("test.txt",'r',encoding = 'utf-8') as f:
    for line in f:
        if line[0] = '1' or line[0] = '0':
          write += [line]

我希望这对你有用:)

file = open("text.txt", "r+")

text_list = [line for line in file.readlines() if line.split()[0] in ["0", "1"]]

file.truncate(0)
file.seek(0)
file.write("".join(text_list))
file.close()