【发布时间】:2018-07-19 11:47:16
【问题描述】:
我想访问大约 5000 个文件并一个一个地处理它们。有什么方法可以连续访问每个文件而不用硬编码每个文件的名称?
【问题讨论】:
标签: python jupyter-notebook file-access
我想访问大约 5000 个文件并一个一个地处理它们。有什么方法可以连续访问每个文件而不用硬编码每个文件的名称?
【问题讨论】:
标签: python jupyter-notebook file-access
以下示例来自此tutorial。
import os, sys
# Open a file
path = "/var/www/html/"
dirs = os.listdir( path )
# This would print all the files and directories
for file in dirs:
print file
【讨论】:
如果你的目录包含父目录和文件,你可以使用os.walk() like -
# Example taken from os.walk documentation
import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
print(root, "consumes", end=" ")
print(sum(getsize(join(root, name)) for name in files), end=" ")
print("bytes in", len(files), "non-directory files")
if 'CVS' in dirs:
dirs.remove('CVS')
或者你可以使用scandir -
for entry in os.scandir(path):
...
【讨论】: