终极目标:迭代文件夹中的多个文件以执行一系列特定任务。
即时目标:加载下一个文件(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.txt
和etc...
),以便继续执行任务
问题:
1)如何将此代码放在for
循环中? (所以我可以加载,并对所有文件执行任务)?
答案 0 :(得分: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 ...