在python

时间:2016-06-01 13:34:39

标签: python python-2.7 delete-row

我是python的初学者,我现在正在练习。

所以我想做的是一个脚本,它找到一个我用raw_input编写的行,它将在多个文件中搜索这一行并删除它。 这样的东西,但更多的文件:

word = raw_input("word: ")
f = open("file.txt","r")
lines = f.readlines()
f.close()
f = open("file.txt","w")
for line in lines:
  if line!=mail+"\n":
    f.write(line)
f.close()

这是一项简单的任务,但实际上我很难在任何地方找到一个例子。

2 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

source = '/some/dir/path/'
for root, dirs, filenames in os.walk(source):
    for f in filenames:
        this_file = open(os.path.join(source, f), "r")
        this_files_data = this_file.readlines()
        this_file.close()
        # rewrite the file with all line except the one you don't want
        this_file = open(os.path.join(source, f), "w")
        for line in this_files_data:
            if line != "YOUR UNDESIRED LINE HERE":
                this_file.write(line)
        this_file.close()

答案 1 :(得分:1)

不是将整个文件读入内存,而是应该遍历文件并将正常的行写入临时文件。完成整个文件后,将其删除并将临时文件重命名为原始文件的名称。这是您将来最常遇到的经典模式。

我还建议将其分解为功能。您应该首先编写代码,以便仅从单个文件中删除所有出现的行。然后你可以编写另一个函数来简单地遍历文件名列表并调用第一个函数(对单个文件进行操作)。

要获取目录中所有文件的文件名,请使用os.walk。如果您不想将此函数应用于目录中的所有文件,则可以自己设置files变量以存储所需的任何文件名配置。

import os


def remove_line_from_file(filename, line_to_remove, dirpath=''):
    """Remove all occurences of `line_to_remove` from file
    with name `filename`, contained at path `dirpath`.
    If `dirpath` is omitted, relative paths are used."""
    filename = os.path.join(dirpath, filename)
    temp_path = os.path.join(dirpath, 'temp.txt')

    with open(filename, 'r') as f_read, open(temp_path, 'w') as temp:
        for line in f_read:
            if line.strip() == line_to_remove:
                continue
            temp.write(line)

    os.remove(filename)
    os.rename(temp_path, filename)


def main():
    """Driver function"""
    directory = raw_input('directory: ')
    word = raw_input('word: ')

    dirpath, _, files = next(os.walk(directory))

    for f in files:
        remove_line_from_file(f, word, dirpath)

if __name__ == '__main__':
    main()

<强> TESTS

所有这些文件都在同一目录中。左边是他们在运行命令之前的样子,右边是他们之后的样子。 &#34;字&#34;我输入的是Remove this line

A.TXT

Foo                                           Foo
Remove this line                              Bar
Bar                                           Hello
Hello                                         World
Remove this line
Remove this line
World

b.txt

Nothing                                       Nothing
In                                            In
This File                                     This File
Should                                        Should
Be Changed                                    Be Changed

c.txt

Remove this line

d.txt

The last line will be removed                 The last line will be removed
Remove this line