如何使用python覆盖或删除文件中的行

时间:2020-09-11 12:45:40

标签: python file

我从迭代器获取数据流,我想将其转储到文件中。我现在正在按照以下步骤进行操作

data_stream = range(100)    # for simplicity

with open('mydump', 'wb') as fh:
    for new_line in data_stream:
        new_line_data = str(new_line)+'\n'
        fh.write(new_line_data.encode())

这里我需要一种功能,可以根据条件返回并删除一些行。

with open('mydump', 'wb') as fh:
    for new_line in data_stream:
        new_line_data = str(new_line)+'\n'
        fh.write(new_line_data.encode())
        if 'delete' in new_line:
            fh.seek(0)
            fh.delete() # how to delete first line (or nth line)

0 个答案:

没有答案