如何保存函数中操作的文件名?

2024-04-26 10:11:28 发布

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

我有一个python函数,它对文件夹中的每个文本文件执行操作。我想保存操作的每个文件的名称,以便函数返回文件名和其他结果。你知道吗

我尝试了以下各种方法。你知道吗

这将获取所有文件名,但是对于每个迭代中的所有文件,而不是操作的单个文件。你知道吗

import re, glob, os, pandas as pd
from pathlib import Path

def sections(file_name):    


    with open(file_name,'r') as f:  
        text = f.read()

        doc = textacy.preprocess.normalize_whitespace(text)
        votes = re.findall(r"Voting[\s*]\D+.+", doc)
        provisions = re.findall(r"Provisions+([\s\S]*?)(?=authorized)", doc)
        name = os.path.splitext(file_name)[0]        

        return name, board, votes, provisions


file_dir = Path(r"path")  
all_files = file_dir.glob("*.txt")  
results = [sections(f) for f in all_files]

print(results)

这是可行的,但在函数中不起作用,最好是从函数中获得,而不是与结果相结合。你知道吗

files = [f for f in glob.glob(path + "**/*.txt", recursive=True)]

files = pd.DataFrame(files)
files.columns = ['file_name']
files['file_name'] = files['file_name'].replace(r'.*(?=\\).','', regex=True) 

当函数返回时,我希望文件名包含在其他变量中。你知道吗


Tags: 文件path函数nameimportredocos