我编写了以下代码来获取sub_folder中文件的路径。
import os
os.chdir('C:\Users\mike\Desktop\a')
base_dir = os.getcwd()
sub_dirs = [os.path.join(base_dir, d) for d in os.listdir(base_dir)]
for i in os.listdir(sub_dirs):
path = [os.path.join(sub_dirs), i]
但它不起作用,我收到此错误: Traceback(最近一次调用最后一次): 文件“C:\ Users \ mike \ Desktop \ mine1.py”,第6行,in 对于os.listdir(sub_dirs)中的m: TypeError:强制转换为Unicode:需要字符串或缓冲区,列出找到
问题是什么?
干杯
答案 0 :(得分:0)
以下是否解决了您的问题?
import os
os.chdir('C:\Users\mike\Desktop\a')
rootDir = os.getcwd()
fileSet = set()
for dir_, _, files in os.walk(rootDir):
for fileName in files:
relDir = os.path.relpath(dir_, rootDir)
relFile = os.path.join(relDir, fileName)
fileSet.add(relFile)
答案 1 :(得分:0)
Hooray for recursion!
def recurse(files, directory):
for item in os.listdir(directory):
full_path = os.path.join(directory, item)
if os.path.isdir(full_path):
recurse(files, full_path)
else:
files.append(full_path)
files = []
recurse(files, 'C:\Users\mike\Desktop\a')
现在你的"文件"列表将被填写。
如果您希望能够遍历每个目录的内容,可以将它们放在子列表中:
def recurse(directories, directory):
files = []
for item in os.listdir(directory):
full_path = os.path.join(directory, item)
if os.path.isdir(full_path):
recurse(directories, full_path)
else:
files.append(full_path)
if len(files) > 0:
directories.append((directory, files))
directories = []
recurse(directories, 'C:\Users\mike\Desktop\a')
for directory, files in directories:
# "directory" is provided as reference (eg "C:\Users\mike\Desktop\a\a1")
for path in files:
# loop over each file in "directory"
pass