[英]Python: List drives, files in subdirectories and sort by extension
I'm trying to write codes as per subject for a project however encounter error.我正在尝试根据项目的主题编写代码,但遇到错误。 Found a few scripts and merged them but apparently didn't work out as I though it would be.找到了一些脚本并将它们合并,但显然没有像我想象的那样工作。
Basically the objective is to:基本上目标是:
Here are my complied codes:这是我编译的代码:
import os
import os.path
dr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
drives = ['%s: '%d for d in dr if os.path.exists('%s: '%d)]
def convert(list):
return tuple(list)
listdrives = convert(drives)
for root, dirname, files in os.walk(listdrives):
for x in files:
x.sort(key=lambda f: os.path.splitext(f)[1])
print(x)
Here is the error message:这是错误消息:
Traceback (most recent call last):
File "d:/WORK/testlist.py", line 11, in <module>
for root, dirname, files in os.walk(listdrives):
File "C:\Users\MHKHR\AppData\Local\Programs\Python\Python38-32\lib\os.py", line 339, in walk
top = fspath(top)
TypeError: expected str, bytes or os.PathLike object, not tuple
I would be glad if anyone could take a look at it!如果有人可以看一下,我会很高兴! Thanks!谢谢!
EDIT编辑
In addition, I encounter a syntax error when exporting to xlsx.另外,我在导出到 xlsx 时遇到语法错误。 I just couldn't figure out why我只是想不通为什么
import os
import os.path
import xlsxwriter
dr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
drives = ['%s:/'%d for d in dr if os.path.exists('%s:' % d)]
for drive in drives:
for res in os.walk(drive):
root, directories, files = res
files.sort(key=lambda f: os.path.splitext(f)[1])
files = [os.path.join(root, f) for f in files]
return directories
return files
workbook = xlsxwriter.workbook('D:\\WORK\\test.xlsx')
worksheet = workbook.add_worksheet()
#set column length
worksheet.set_column('A:A', 80)
worksheet.set_column('B:B', 80)
#write headers
worksheet.write('A1', 'Directories')
worksheet.write('B1', 'Files')
dirts = (directories)
fil = (files)
for d1 in range(len(dirts)):
worksheet.write(d1+1, 0, dirts[d1])
worksheet.write(d1+1, 1, fil[d1])
workbook.close()
Here's something that has worked locally on my Windows machine:这是在我的 Windows 机器上本地工作的东西:
import os
import os.path
dr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
drives = ['%s:/'%d for d in dr if os.path.exists('%s:' % d)]
for drive in drives:
for res in os.walk(drive):
root, directories, files = res
files.sort(key=lambda f: os.path.splitext(f)[1])
files = [os.path.join(root, f) for f in files]
print(directories)
print(files)
Your initial error that led to the traceback in your question was due to the fact that you can't os.walk
on a list, you have to os.walk
on a directory path and walk on each drive.导致问题回溯的初始错误是由于您无法在列表中使用os.walk
,您必须在目录路径上使用os.walk
并在每个驱动器上进行操作。
I had an issue with using the backslash for the drives
variable, play around with which works.我在使用drives
变量的反斜杠时遇到了问题,玩弄哪个有效。
You also shouldn't call sort on an individual object in a list, rather the entire list object.您也不应该对列表中的单个 object 而不是整个列表 object 调用排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.