【问题标题】:Extracting specific value from multiple text files from folder using python and store it in Excel sheet使用python从文件夹中的多个文本文件中提取特定值并将其存储在Excel工作表中
【发布时间】:2021-12-07 05:36:57
【问题描述】:

我在一个文件夹中有多个文本文件,其中数据的形式是- text file 1text file 2

我想从文本文件 1 中提取文件名和 IOS 值,从文本文件 2 中提取文件名和 MB/s 值并将其存储在 excel 文件中

这是我的代码-

import os

path = "Folder Path"
os.chdir(path)

def read_text_file(file_path):
    with open(file_path, 'r') as f:
        print(f.read())
  
for file in os.listdir():
    if file.endswith(".txt"):
        file_path = f"{path}\{file}"
  
        read_text_file(file_path)

with open ('text file 1.txt') as f:
for line in f:
    read = line.spilt(" ")
    print (IOS)

with open ('text file 2.txt') as f:
for line in f:
    read = line.spilt(" ")
    print (BW)MB/s
  

我该如何解决这个问题?

【问题讨论】:

  • 您提供的代码包含许多语法错误。你需要修复这些。然后你需要决定文件格式规则是什么。文件名是否与文件中的第一行相同(减去冒号)? IOS令牌总是在最后一行吗?一旦您认为通过它应该非常简单
  • @BrutusForcus 是的,文件名与文件中的第一行相同,IOS 和 MB/s 不是文本文档的最后一行,为方便起见,我裁剪了其余数据跨度>

标签: python excel txt


【解决方案1】:

根据 cmets 中所说的内容,这里有一种方法可以在给定文件夹中的所有文本 (.txt) 文件中搜索此代码中正则表达式中定义的模式。代码将发出 IOS 值和找到它的文件的名称。

from glob import glob
import os
import re

FOLDER = 'foo' # the folder where the txt files can be found

for txt in glob(os.path.join(FOLDER, '*.txt')):
    with open(txt) as tfile:
        for line in tfile:
            if (m := re.match('.*IOS=(?P<IOS>.*),.*BW=(?P<BW>.*) ', line)):
                print(f'filename={txt}, IOS={m.group("IOS")} BW={m.group("BW")}')
                break

【讨论】:

  • 我只需要文本文件 1 的 IOS 值和文本文件 2 的 MB/s 值 ....你能建议我怎么做吗
  • 这不是所有的功课,我只是寻求帮助以提取 MB/s 值...
  • 我在我的代码中增强了 RE。也许这会对你有所帮助
猜你喜欢
  • 2014-12-23
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 2018-11-12
  • 1970-01-01
  • 1970-01-01
  • 2022-12-04
  • 1970-01-01
相关资源
最近更新 更多