【问题标题】:How to extract a string from the file list in Python?如何从 Python 中的文件列表中提取字符串?
【发布时间】:2018-08-02 01:16:15
【问题描述】:

我有一个文件夹,其中包含 425 个类似文件的列表,名为“00001q1.txt、00002w2.txt、00003e3.txt... 00425q1.txt”。每个文件在两行之间包含一行文本。这些行在所有文件中都是不变的。我需要提取这些行并将其作为行列保存到输出文件中。

这是一个能够循环文件夹中所有文件的脚本,但它不会从文件列表中提取所需的行到 otput 文件。

#!/usr/bin/python
# Open a file

import re
import os
import sys
import glob

outfile = open("list7.txt", "w")

# This would print all the files and directories (in sorted order) 
full_path = r"F:\files\list"
filelist = sorted(os.listdir( full_path ))
print filelist

# This would scan the filelist and extract desired line that located between two rovs:
# 00001q1.txt:
# Row above line
# line
# Row under line

buffer = []
for line in filelist:
    if line.startswith("Row above line"):
        buffer = ['']
    elif line.startswith("Row under line"):
        outfile.write("".join(buffer))
        buffer = []
    elif buffer:
        buffer.append(line)

# infile.close()
outfile.close()

如果我在脚本中定义了一个文件(例如 00001q1.txt“)而不是文件列表,则所需的行将成功写入输出文件。我应该怎么做那个脚本扫描文件列表?

提前致谢。

【问题讨论】:

  • 你应该有 2 个嵌套循环:for file in filelist:for line in open(file):

标签: python string python-2.7 file find


【解决方案1】:

如果我理解你想写信给list7.txt所有需要的事件:

import os

outfile = open("list7.txt", "w")

full_path = r"F:\files\list"
filelist = sorted(os.listdir(full_path))

with open("list7.txt", "w") as outfile:
    buffer = []
    for filename in filelist:
        with open(os.path.join(full_path, filename), "r") as infile:
            for line in infile.readlines():
                if line.startswith("Row above line"):
                    buffer = ['']
                elif line.startswith("Row under line"):
                    outfile.write("".join(buffer))
                    buffer = []
                elif buffer:
                    buffer.append(line)
            for line in buffer:
                outfile.write(line)

【讨论】:

  • 在写入输出文件之前,终于不需要使用buffer 变量来缓存每一行了。您可以在阅读循环中直接将每次出现的地方都写在那里。
  • 非常感谢您的回答。但是编译器在包含文件的文件夹中找到第一个文件并显示以下消息: Traceback (last recent call last): File "F:\files\list", line 19, in with open(fileName, 'rU' ) as f: IOError: [Errno 2] No such file or directory: '00001q1.txt' 可能是因为使用了“with open”构造吗?有没有替代品?
  • 如果您的当前目录(即您的模块的默认文件夹)不在F:\files\list 中,您必须在open 语句中加入该文件夹的最终路径:os.path.join(full_path, filename)。我已经更新了 sn-p。
【解决方案2】:

您需要在每个文件中迭代文件和行

buffer = []
for fileName in filelist:
    with open(fileName, 'rU') as f:
      for line in f:
        if line.startswith("Row above line"):
          buffer = ['']
        elif line.startswith("Row under line"):
          outfile.write("".join(buffer))
          buffer = []
        elif buffer:
          buffer.append(line)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    相关资源
    最近更新 更多