我正在探索 python 并尝试按最后修改时间对目录中的所有文件进行排序,然后将列表写入 txt 文件。
import time
import os
i=1
a="path"
def getfiles(dirpat):
b = [s for s in os.listdir(dirpat)
if os.path.isfile(os.path.join(dirpat, s))]
b.sort(key=lambda s: os.path.getmtime(os.path.join(dirpat, s)))
return b
lyst=[]
testfile='c://test.txt'
lyst=getfiles(a)
for x in range (0,len(lyst)):
print lyst[x]
fileHandle = open (testfile, 'w' )
fileHandle.write ("\n".join(str(lyst[x])))
fileHandle.close()
它打印完美并且还按日期排序
example1.pdf
example3.docx
example4.docx
exmaple2.docx
example 5.doc
但是当我打开文件时,它只有最后一个条目并像这样显示
e
x
a
... and so on
就是想不通问题出在哪里。如果我删除“\n”.join,它只会打印最后一个条目。
提前致谢, 尼尔斯
请您参考如下方法:
更正join(),例如:
'\n'.join(str(path) for path in list)
并且请重命名“list”变量,因为list 是Python 的内置数据类型。
