繁体   English   中英

使用python从文件夹中的多个文本文件中提取特定值并将其存储在Excel工作表中

[英]Extracting specific value from multiple text files from folder using python and store it in Excel sheet

我在一个文件夹中有多个文本文件,其中数据是文本文件 1文本文件 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
  

我该如何解决这个问题?

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

from glob import glob
import os
import re

FOLDER = 'foo' # the folder where the txt files can be found
cre = re.compile('.*IOS=(.*),.*')

for txt in glob(os.path.join(FOLDER, '*.txt')):
    with open(txt) as tfile:
        for line in tfile:
            if (m := cre.match(line)):
                print(f'filename={txt}, IOS={m.group(1)}')
                break

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM