自动列出 Python 中多个目录中的文件的方法
Automated way to list files from multiple directories in Python
我需要创建一个包含多个目录中所有文件的列表。
我有 all_dir
,其中包含 dir1, dir2, dir3...
。每个目录包含多个文件['text1.txt','text2.txt'...]
。
虽然我能够创建单个目录的列表,但我找不到自动化的方法。
这就是我所拥有的,它适用于单个目录。
path = '../all_dir'
list1 = [f for f in os.listdir(os.path.join(path, 'dir1')
list2 = [f for f in os.listdir(os.path.join(path,'dir1')
#etc...
这就是我正在考虑的代码:
all_list = []
for dir1 in os.listdir(path):
current = os.listdir(os.path.join(path,dir1))
all_list.append(current)
但是这个 for 循环引发: NotADirectoryError
为了解决这个问题我试过了
all_list = []
for dir1 in os.listdir(path):
current = os.walk(os.path.join(path,dir1))
all_list.append(current)
但是这个循环引发了一个 <generator object walk at 0x100ca4e40>
的列表
你能帮忙吗?
listdir
也会返回文件,所以在 for 循环中你应该检查它是否是目录。您可以使用 os.path.isdir()
for dir1 in os.listdir(path):
full_path = os.path.join(path, dir1)
if os.path.isdir(full_path):
current = os.listdir(full_path)
all_list += current
#Navigate to the location where all_dir is
os.chdir('../all_dir')
#l is the list of paths of each directory in all_dir
l = []
for folder in os.listdir(os.getcwd()):
path = os.path.join(os.getcwd(), folder)
l.append(path)
#all files in all directories will be stored in all_list
all_list=[]
for i in li:
os.chdir(i)
#'*.*' prints files only (ended with any extension), if you want to print everything (including) in each directory use '*'
all_files = glob.glob('*.*')
for f in all_files:
all_list.append(f)
#number of all files
len(all_list)
#print all files
print(all_list)
我需要创建一个包含多个目录中所有文件的列表。
我有 all_dir
,其中包含 dir1, dir2, dir3...
。每个目录包含多个文件['text1.txt','text2.txt'...]
。
虽然我能够创建单个目录的列表,但我找不到自动化的方法。
这就是我所拥有的,它适用于单个目录。
path = '../all_dir'
list1 = [f for f in os.listdir(os.path.join(path, 'dir1')
list2 = [f for f in os.listdir(os.path.join(path,'dir1')
#etc...
这就是我正在考虑的代码:
all_list = []
for dir1 in os.listdir(path):
current = os.listdir(os.path.join(path,dir1))
all_list.append(current)
但是这个 for 循环引发: NotADirectoryError
为了解决这个问题我试过了
all_list = []
for dir1 in os.listdir(path):
current = os.walk(os.path.join(path,dir1))
all_list.append(current)
但是这个循环引发了一个 <generator object walk at 0x100ca4e40>
你能帮忙吗?
listdir
也会返回文件,所以在 for 循环中你应该检查它是否是目录。您可以使用 os.path.isdir()
for dir1 in os.listdir(path):
full_path = os.path.join(path, dir1)
if os.path.isdir(full_path):
current = os.listdir(full_path)
all_list += current
#Navigate to the location where all_dir is
os.chdir('../all_dir')
#l is the list of paths of each directory in all_dir
l = []
for folder in os.listdir(os.getcwd()):
path = os.path.join(os.getcwd(), folder)
l.append(path)
#all files in all directories will be stored in all_list
all_list=[]
for i in li:
os.chdir(i)
#'*.*' prints files only (ended with any extension), if you want to print everything (including) in each directory use '*'
all_files = glob.glob('*.*')
for f in all_files:
all_list.append(f)
#number of all files
len(all_list)
#print all files
print(all_list)