在Python中打开输入和输出文件

ast*_*y13 2 python file python-3.x

我有以下代码,旨在删除文件的特​​定行.当我运行它时,它会打印出目录中的两个文件名,然后删除其中的所有信息.我究竟做错了什么?我在Windows下使用Python 3.2.

import os

files = [file for file in os.listdir() if file.split(".")[-1] == "txt"]

for file in files:
    print(file)
    input = open(file,"r")
    output = open(file,"w")

    for line in input:
        print(line)
        # if line is good, write it to output

    input.close()
    output.close()
Run Code Online (Sandbox Code Playgroud)

Fre*_*Foo 7

open(file, 'w')擦除文件.为防止这种情况,请在r+模式下打开(读取+写入/不擦除),然后立即读取所有内容,过滤行,然后再将其写回.就像是

with open(file, "r+") as f:
    lines = f.readlines()              # read entire file into memory
    f.seek(0)                          # go back to the beginning of the file
    f.writelines(filter(good, lines))  # dump the filtered lines back
    f.truncate()                       # wipe the remains of the old file
Run Code Online (Sandbox Code Playgroud)

我假设这good是一个函数,告诉我是否应该保留一条线.