排序/删除文件行

2024-06-17 14:59:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想去掉文件中少于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

提前谢谢!你知道吗


Tags: 文件字符串代码importtxtlenifline
2条回答

使用迭代器而不是列表来支持很长的文件:

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)

您需要使用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()

相关问题 更多 >