使用os python迭代文件夹中的文件

问题描述 投票:0回答:1

终极目标:迭代文件夹中的许多文件以执行特定的任务集。

立即目标:加载下一个文件(file2)以执行任务

背景:我使用以下代码

import os

folder = '/Users/eer/Desktop/myfolder/'

for subdir, dirs, files in os.walk(folder):
    for item in os.listdir(folder):
        if not item.startswith('.') and os.path.isfile(os.path.join(folder, item)): #gets rid of .DS_store file
            print(item)

输出:print(item)

file1.txt
file2.txt
file3.txt
(etc...)

我使用以下代码打开第一个file

data_path = folder + item
file = open(data_path, "r")

#perform a set of tasks for this file

这适用于打开第一个文件file1.txt并执行一组任务。

但是,我不知道如何加载file2.txt(最终加载file3.txtetc...)以便我可以继续执行任务

问题:

1)如何将此代码放在for循环中? (所以我可以加载,并对所有文件执行任务)?

python-3.x for-loop if-statement operating-system folder
1个回答
2
投票

您可以在同一个循环中执行文件操作,如:

import os

folder = '/Users/eer/Desktop/myfolder/'

for subdir, dirs, files in os.walk(folder):
    for item in os.listdir(folder):
        if not item.startswith('.') and os.path.isfile(os.path.join(folder, item)):
            data_path = folder + item
            with open(data_path, "r") as file:
                ... use file here ...
© www.soinside.com 2019 - 2024. All rights reserved.