首页 > 解决方案 > 如何遍历文件夹中的每个文件,对文件执行一些操作并将输出保存到另一个文件夹中的文件 Python

问题描述

我有一个包含多个文件的文件夹,如下所示:

1980

1981年

1982年

每个文件中都有一些文本。我想遍历这些文件中的每一个并对每个文件进行一些操作,然后将编辑后的文件保存到另一个文件夹并移至下一个文件,依此类推。结果将是我有原始文件夹,然后是另一个文件夹,其中包含每个文件的编辑版本,如下所示:

1980_过滤

1981_过滤

1982_过滤

是否有可能做到这一点?

目前我有一些代码循环遍历文件夹中的文件,对每个文件进行一些过滤,然后将每个文件的所有编辑保存到一个大文件中。这是我的代码:

import os
input_location = 'C:/Users/User/Desktop/mini_mouse'
output_location = 'C:/Users/User/Desktop/filter_mini_mouse/mouse'
for root, dir, files in os.walk(input_location):
    for file in files:
        os.chdir(input_location)
        with open(file, 'r') as f, open('NLTK-stop-word-list', 'r') as f2:
            mouse_file = f.read().split()  # reads file and splits it into a list
            stopwords = f2.read().split()
            x = (' '.join(i for i in mouse_file if i.lower() not in (x.lower() for x in stopwords)))
            with open(output_location, 'a') as output_file:
                output_file.write(x)

任何帮助将不胜感激!

标签: pythonfilenltkfile-handlingn-gram

解决方案


首先你应该从打开NLTK-stop-word-list唯一一次开始,所以我把它移到你的循环之外。其次,os.chdir()是多余的,你可以os.path.join()用来获取你当前的文件路径(并构造你的新文件路径):

import os
input_location = 'C:/Users/User/Desktop/mini_mouse'
output_location = 'C:/Users/User/Desktop/filter_mini_mouse/'
stop_words_path = 'C:/Users/User/Desktop/NLTK-stop-word-list.txt'
with open(stop_words_path, 'r') as stop_words:
    for root, dirs, files in os.walk(input_location):
        for name in files:
            file_path = os.path.join(root, name)
            with open(file_path, 'r') as f:
                mouse_file = f.read().split()  # reads file and splits it into a list
                stopwords = stop_words.read().split()
                x = (' '.join(i for i in mouse_file if i.lower() not in (x.lower() for x in stopwords)))
                new_file_path = os.path.join(output_location, name) + '_filtered'
                with open(new_file_path, 'a') as output_file:
                    output_file.write(x)

PS:我冒昧地更改了您的一些变量名,因为它们是python内置单词('file'和'dir')的一部分。如果你跑__builtins__.__dict__.keys(),你会在那里看到它们。


推荐阅读