如何从大量(4.5m)文件中提取特定行并正确调试?

2024-06-17 18:16:54 发布

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

我有一个关于数据操作和提取的问题。你知道吗

我有大量的文件(大约450万个文件),我想从每个文件中提取第三行(行)并将其保存到一个新文件中。但是,由于文件数和提取的行数的不同,缺少的行数似乎只有5行。你知道吗

我试过调试以查看错误发生的位置。出于调试目的,我可以想到两个可能的问题: (1) 我计算的行数不正确(我尝试了两种行计数算法,它们似乎匹配) (2) 它读取一个空字符串,我也尝试在代码中调试它。还有什么其他的可能性,我可以期待调试?你知道吗

计算文件长度1的算法

def file_len(filename):
    with open(filename) as f:
        for i, l in enumerate(f):
        pass
    return i + 1

计算文件长度2的算法

def file_len2(filename):
    i = sum(1 for line in open(filename))
    return i

3号线提取算法

def extract_line(filename):
    f = open(filename, 'r')
    for i, line in enumerate(f):
        if i == 2: # Line number 3
            a = line
    if not a.strip():
        print(Error!)
    f.close()
    return a

没有错误消息。 我希望输入文件的数量与输出文件中的行数相匹配,但两者之间的差异很小,大约为450万行中的5行。你知道吗


Tags: 文件数据in目的算法forreturnif
2条回答

你的总体想法是正确的,但事情可以简单一点。你知道吗

我还假设差异是由于第三行是空的,或者少于3行的文件造成的。。你知道吗

def extract_line(filename):
  with open(filename) as f:
    for line_no, line_text in enumerate(f):
    if line_no == 2:
      return line_text.strip()  # Stop searching, we found the third line
  # Here file f is closed because the `with` statement's scope ended.
  # None is implicitly returned here.

def process_files(source_of_filenames):
  processed = 0  # Count the files where we found the third line.
  for filename in source_of_filenames:
    third_line = extract_line(filename)
    if third_line:
      processed += 1  # Account for the success.
      # Write the third line; given as an illustration.
      with open(filename + ".3rd-line", "w") as f:
        f.write(third_line)
    else:
      print("File %s has a problem with third line" % filename);
  return processed

def main():  # I don't know the source of your file names.
  filenames = # Produce a list or a generator here.
  processed = process_files(filenames)
  print("Processed %d files successfully", processed)

希望这有帮助。你知道吗

建议:如果全局设置了a,检查是否少于三行将失败。你知道吗

(我会把这个放在评论里,但我没有足够的代表)

相关问题 更多 >