如何在python中从文件中删除行

如何在python中从文件中删除行,python,Python,可能重复: 我需要从文件f中删除包含数字“2”的行= 2 3 5 6 7 2 4 5 如果要编辑文件,请使用正确的数据创建一个新文件,然后将新文件重命名为旧文件。这就是像文本编辑器这样的严肃程序可能会做的事情。(有些文本编辑器实际上会做更奇怪的事情,但这是没有用的。)这是因为在许多文件系统中,重命名可以是原子的,因此在任何情况下都不会导致原始文件损坏 这将导致代码产生以下效果: with open(orig_file) as f, open(working_file, "w") as wor

可能重复:

我需要从文件f中删除包含数字“2”的行=

2 3
5 6
7 2
4 5

如果要编辑文件,请使用正确的数据创建一个新文件,然后将新文件重命名为旧文件。这就是像文本编辑器这样的严肃程序可能会做的事情。(有些文本编辑器实际上会做更奇怪的事情,但这是没有用的。)这是因为在许多文件系统中,重命名可以是原子的,因此在任何情况下都不会导致原始文件损坏

这将导致代码产生以下效果:

with open(orig_file) as f, open(working_file, "w") as working: 
    # ^^^ 2.7+ form, 2.5+ use contextlib.nested
    for line in f:
        if '2' not in line: # Is this exactly the criterion you want?
                            # What if a line was "12 5"?
            working.write(line)

os.rename(working_file, orig_file)

您可能需要使用
orig_file+'~'
tempfile
模块来生成工作文件。

data=''.join(如果'2'不在l.split('')中,则为f中的l)。语法错误:无效syntax@ammar刷新页面;)。但事实上,这个版本在f中遗漏了一个
data=''.join(如果'2'不在l.split('')中,则在f中l代表l))
。data='.join(lambda l:'2'不在l.strip().split(''),f)TypeError:join()正好有一个参数(给出了2个参数)@ammar我在这里指责时间太晚了。更正了,当我将
过滤器调用从shell复制到stackoverflow时,不知何故我忘记了它。抱歉。请注意,此方法允许文件因意外终止而损坏。
import fileinput
for line in fileinput.input('f',inplace =1):
  line = line.strip()
  if not '2' in line:
    print line 
import fileinput
for line in fileinput.input('f',inplace =1):
  line = line.strip()
  if not '2' in line:
    print line