Python 3.x 使用os python对文件夹中的文件进行迭代

Python 3.x 使用os python对文件夹中的文件进行迭代,python-3.x,for-loop,if-statement,operating-system,directory,Python 3.x,For Loop,If Statement,Operating System,Directory,最终目标:迭代文件夹中的多个文件以执行一组特定任务 当前目标:加载下一个文件(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

最终目标:迭代文件夹中的多个文件以执行一组特定任务

当前目标:加载下一个文件(
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)
输出:
打印(项目)

我正在使用以下代码打开第一个
文件

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

#perform a set of tasks for this file
这对于打开第一个文件
file1.txt
和执行一组任务非常有效

但是,我不确定如何加载
file2.txt
(最终加载
file3.txt
等…
),以便继续执行任务

问题:


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

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

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 ...

是否将处理置于
for
循环中?我不明白你在问什么。我刚刚更新了我的问题…但是,是的,一个for循环,如果这能解决问题,你已经有了
for
循环,它就是你的
打印
语句的地方。。。
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 ...