我想要删除少于6个字符的文件中的行,并删除字符串少于6个字符的整行。我尝试运行此代码,但最终删除了整个文本文件。我该怎么做呢?
代码:
import linecache
i = 1
while i < 5:
line = linecache.getline('file.txt', i)
if len(line) < 6:
str.replace(line, line, '')
i += 1
提前致谢!
答案 0 :(得分:2)
您想要使用open方法而不是linecache:
def deleteShortLines():
text = 'file.txt'
f = open(text)
output = []
for line in f:
if len(line) >= 6:
output.append(line)
f.close()
f = open(text, 'w')
f.writelines(output)
f.close()
答案 1 :(得分:1)
使用迭代器代替列表来支持很长的文件:
with open('file.txt', 'r') as input_file:
# iterating over a file object yields its lines one at a time
# keep only lines with at least 6 characters
filtered_lines = (line for line in input_file if len(line) >= 6)
# write the kept lines to a new file
with open('output_file.txt', 'w') as output_file:
output_file.writelines(filtered_lines)