簡體   English   中英

如何為文件夾/目錄中的所有文件運行腳本

[英]How to run script for all files in a folder/directry

我是python的新手。 我已經成功編寫了一個腳本來使用以下命令在文件中搜索內容:

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

有沒有辦法對文件夾中的所有文件執行搜索功能? 因為當前,我必須通過以下命令手動更改腳本的文件名: open(r"C:\\file.txt), open(r” C:\\ file1.txt) , open(r“ C:\\ file2.txt) `等

謝謝。

您可以使用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返回(root path, dir names, file names) folder(root path, dir names, file names) tuple ,因此您可以iterate filenames並使用os.path.join(root, filename)打開每個文件os.path.join(root, filename)基本上將根路徑與文件名,以便您可以打開文件。

您可以使用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

由於您是初學者,因此我將為您提供一個簡單的解決方案並逐步解決。

導入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

如果您需要有關概念的幫助,請參考以下內容:

對於p3中的循環: http ://www.python-course.eu/python3_for_loop.php

os函數庫(其中包含一些很棒的東西): https : //docs.python.org/2/library/os.html

祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM