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:
'\n'.join(str(path) for path in list)
And please rename the "list" variable, because list is a built-in data type in Python.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With