首页 > 解决方案 > 如果超过 x 个字符,如何从文件中删除行

问题描述

我怎么能做这样的事情?

with open(r'C:\some_list.txt') as f:
    list = f.readlines()
for line in list:
    if line: #has more than x characters
        delete line

标签: pythonpython-3.x

解决方案


如果文件相当小,最简单的方法是全部读入,过滤,然后全部写出。

with open(r'C:\some_list.txt')  as f:
    lines = f.readlines()

# Keep lines <= 10 chars long with a list comprehension
filtered_lines = [line for line in lines if len(line) > 10]

# Do what you like with the lines, e.g. write them out into another file:
with open(r'C:\filtered_list.txt', 'w') as f:
    for line in filtered_lines:
        f.write(line)

如果要将匹配的行流式传输到另一个文件中,那就更容易了:

with open(r'C:\some_list.txt') as in_file, open(r'C:\filtered_list.txt', 'w') as out_file:
    for line in in_file:
        if len(line) <= 10:
            out_file.write(line)

推荐阅读