如何为文件夹/ directry中的所有文件运行脚本

时间:2017-06-22 14:42:57

标签: python

我是python的新手。我已经成功编写了一个脚本来使用以下方法搜索文件中的内容:

open(r"C:\file.txt)re.search功能,一切正常。

有没有办法对文件夹中的所有文件执行搜索功能?因为目前,我必须手动更改我的脚本的文件名open(r"C:\file.txt), open(r“C:\ file1.txt), open(r”C:\ file2.txt)`等

感谢。

3 个答案:

答案 0 :(得分:0)

您可以使用os.walk检查所有文件,如下所示:

import os
for root, _, files in os.walk(path):
    for filename in files:
        with open(os.path.join(root, filename), 'r') as f:
            #your code goes here

<强>解释

os.walk会在tuple中返回(root path, dir names, file names)的{​​{1}},因此您可以folderiterate并使用{{打开每个文件1}}它基本上将根路径与文件名连接起来,因此您可以打开文件。

答案 1 :(得分:0)

您可以使用os.listdir(path)函数:

import os

path = '/Users/ricardomartinez/repos/Salary-API'

# List for all files in a given PATH
file_list = os.listdir(path)

# If you want to filter by file type
file_list = [file for file in os.listdir(path) if os.path.splitext(file)[1] == '.py']


# Both cases yo can iterate over the list and apply the operations
# that you have

for file in file_list:
    print(file)
    #Operations that you want to do over files

答案 2 :(得分:0)

由于您是初学者,我将为您提供一个简单的解决方案并逐步完成。

导入os模块,并使用os.listdir函数创建目录中所有内容的列表。然后,使用for循环遍历文件。

示例:

# Importing the os module
import os

# Give the directory you wish to iterate through
my_dir = <your directory -  i.e. "C:\Users\bleh\Desktop\files">

# Using os.listdir to create a list of all of the files in dir
dir_list = os.listdir(my_dir)

# Use the for loop to iterate through the list you just created, and open the files
for f in dir_list:
    # Whatever you want to do to all of the files

如果您需要有关概念的帮助,请参阅以下内容:

for po:http://www.python-course.eu/python3_for_loop.php

中的looops

os函数库(其中有一些很酷的东西):https://docs.python.org/2/library/os.html

祝你好运!

相关问题