无法从文本文件中正确删除行

时间:2013-12-01 11:03:43

标签: python line text-files line-breaks

我有一个名为test.txt的文本文件,其中包含以下内容:

This is a test
I want this line removed

我正在尝试在Python 2中编写一个算法来删除第二行(“我希望删除此行”)以及第一行的换行符。我正在尝试将其输出到名为test_2.txt的第二个文件;但是,生成的test_2.txt文件为空,第一行不存在。为什么?这是我的代码:

#coding: iso-8859-1

Fil = open("test.txt", "wb")
Fil.write("This is a test" + "\n" + "I want this line removed")
Fil.close()
Fil = open("test.txt", "rb")
Fil_2 = open("test_2.txt", "wb")

number_of_lines = 0

for line in Fil:
    if line.find("I want") != 0:
        number_of_lines += 1

line_number = 1

for line in Fil:
    if line.find("I want") != 0:
        if line_number == number_of_lines:
            for g in range(0, len(line)):
                if g == 0:
                    a = line[0]
                elif g < len(line) - 1:
                    a += line[g]
            Fil_2.write(a)
        else:
            Fil_2.write(line)
        line_number += 1

Fil.close()
Fil_2.close()

2 个答案:

答案 0 :(得分:2)

您的算法过于复杂。试试这个:

with open('test.txt') as infile, open('test_2.txt', 'w') as outfile:
  for line in infile:
    if not line.startswith("I want"):
      outfile.write(line.strip())

答案 1 :(得分:1)

记住open返回一个迭代器,您可以通过这样编写来简化,并概括解决方案。

with open('test.txt') as infile:
    first_line = next(infile)
    with open('test_2.txt', 'w') as outfile:
        outfile.write(first_line.strip())
# both files will be automatically closed at this point