【问题标题】:Read all files in a directory and output to a single file读取目录中的所有文件并输出到单个文件
【发布时间】:2016-03-31 10:17:40
【问题描述】:

我编写了一个使用正则表达式搜索文件的 python 脚本。它找到一个名称和 2 个数字并将它们写入输出文件。我有一个包含许多文件的文件夹,我想为文件夹中的每个文件自动执行此过程并写入相同的输出文件。

这是我目前的尝试,仅适用于打开单个文件。

import os
import re
directory = os.listdir(os.getcwd())
for files in directory:
    f = open("VALUE_WOOLWORTHS.txt", "r")
    searchlines = f.readlines()
    for line in searchlines:
        if '"Spread" keyvalue' in line:
            n = re.search(r'\keyvalue="(.*)', line)
            name = n.group()
            break
    f.close()
    count = 0
    for i, line in enumerate(searchlines):
        if '"VALUE (Base)">' in line:
            for line in searchlines[i:i+1]:
                m = re.search(r'\d+\.\d+', line)
                count = count + 1
                if count == 1: m1 = m.group()
                    if count == 2: 
                    m2 = m.group()
                    ff = open("test.txt","a")
                    output = '{} {} {}'.format(name, m1, m2)
                    print output
                    ff.write(output)

                if count == 2: 
                break

如何编辑以上内容以顺序打开当前目录中的所有文件,进行搜索,写入相同的输出文件,然后打开下一个文件并重复?我希望每个文件的输出都显示在新行上。

非常感谢

【问题讨论】:

  • 我有点困惑,为什么您需要遍历搜索线两次。我认为您可能可以重构为更易于理解的形式。您是否希望 '"Spread" keyvalue' 在 '"VALUE (Base)">' 之前?您应该提供正在扫描的文件的摘录。
  • 您的缩进是错误的,不允许理解您想要达到的目标。请修复它并考虑添加输入和预期输出的示例。
  • @Spinor yes '"Spread" kevalue' 出现在 '"VALUE (Base)">' 上方 2 行。是的,我知道代码很乱,但由于某种原因,我无法让它正常工作,我认为我留下的不可见空间正在发生一些奇怪的事情。这是一个临时的工作代码。

标签: python regex file-io


【解决方案1】:

假设“VALUE_WOOLWORTHS.txt”是您要读取的文件之一,只需将其更改为files

for files in directory:
    f = open(files, "r")

并且,对于输出文件中的换行符,更改

output = '{} {} {}'.format(name, m1, m2)

output = '{} {} {}\n'.format(name, m1, m2)

,如果您不介意末尾的换行符。

【讨论】:

  • 非常感谢!我想将输出文件中的结果复制粘贴到 excel 中的 3 个相应列中。你知道我该怎么做吗?或者我需要在 python 中更改输出代码吗?
  • @B.狄龙我认为您可以将其保存为 txt 或 csv 文件,然后将其导入 excel。如果您的输出值(namem1m1)不包含空格,则当前输出应该没问题。
猜你喜欢
  • 2013-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-28
  • 2016-11-11
  • 2018-07-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多