我该怎么做?
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
答案 0 :(得分:2)
如果文件很小,最简单的方法是全部读取,过滤并全部写入。
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)
答案 1 :(得分:1)
您可以逐行读取文件,如果通过了限制,则将该行写到新文件中(放弃其他行)。对于大文件,在内存使用方面如此高效:
with open('file_r.txt', 'r') as file_r, open('file_w.txt', 'w') as file_w:
thresh = 3
for line in file_r:
if len(line) < thresh:
file_w.write(line)
答案 2 :(得分:0)
尝试(我以3
为例)
with open(r'C:\some_list.txt') as f:
l = [i for i in f if len(i) > 3]
由于list
是内置的,因此我将l
重命名为list
。
答案 3 :(得分:0)
首先将行保存在列表中,通过逐个阅读不会删除这些行:
the_list = []
with open(r'C:\some_list.txt', "r") as f:
for line in f:
#print(len(line))
if (len(line)) < 50:#here I used 50 charecters
the_list.append(line)
然后将列表写入文件:
with open(r'C:\some_list.txt', 'w') as f:
for line in the_list:
f.write(line)
如果您不想使用列表或文件太大,请尝试:
with open(r'C:\some_list.txt', "r") as f, open('new.txt', 'a') as fw:
for line in f:
if (len(line)) < 50:
fw.write(line)
根据需要替换output.txt。上面的代码将从some_list.txt中逐行读取,然后如果该行少于50个字符,则将其写入“ output.txt”中
答案 4 :(得分:0)
相反,可以这样做:
# fname : file name
# x : number of characters or length
def delete_lines(fname = 'test.txt', x = 8):
with open(fname, "r") as f:
lines = f.readlines()
with open(fname, "w") as f:
for line in lines:
if len(line) <= x:
f.write(line)
delete_lines()
当然,有更好的方法可以做到这一点。