I’m exploring python and tried to sort all files from a directory by last modified and then write the list into a txt file.
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()
It printed perfectly and sorted by date also
example1.pdf
example3.docx
example4.docx
exmaple2.docx
example 5.doc
But when I opened the file, it just had the last entry and displayed it like this
e
x
a
... and so on
Just can’t figure out where the problem lies. If I remove “\n”.join it just prints me the last entry.
Thanks in advance,
Nils
Correct the
join(), e.g:And please rename the “list” variable, because
listis a built-in data type in Python.