我有多个文件夹,每个文件夹包含大约5-10个文件.我要做的是在完成前几个文件夹中的文件处理后转到下一个文件夹,然后开始处理新的文件。我有这样的代码:
for root, dirs, files in os.walk("Training Sets"): #Path that contains folders
for i in dirs: #if I don't have this, an error is shown in line 4 that path needs to be str and not list
for file in i: #indexing files inside the folders
path = os.path.join(i, files) #join path of the files
dataset = pd.read_csv(path, sep='\t', header = None) #reading the files
trainSet = dataset.values.tolist() #some more code
editedSet = dataset.values.tolist() #some more code
#rest of the code...问题是它什么也做不了。如果我添加打印以进行调试,甚至不会打印。
发布于 2022-07-05 16:15:08
首先,确保您位于正确的顶级目录(即包含“培训集”的目录)。您可以使用os.path.abspath(os.curdir)来检查这一点。否则,代码什么也不做,因为它找不到要遍历的目录。
os.walk为您执行目录遍历操作。关键是理解根(当前目录的路径)、dirs (子目录列表)和文件(当前目录中的文件列表)。你其实不需要脏东西。
所以你的代码是两个循环:
>>> for root, dirs, files in os.walk("New Folder1"): #Path that contains folders
... for file in files: #indexing files inside the folders
... path = os.path.join(root, file) #join path of the files
... print(path) # Your code here
...
New Folder1\New folder1a\New Text Document.txt
New Folder1\New folder1b\New Text Document2.txthttps://stackoverflow.com/questions/72872207
复制相似问题