Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python doesn't write all entries from list

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

like image 491
nils Avatar asked Mar 12 '26 11:03

nils


1 Answers

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.

like image 104
Zaur Nasibov Avatar answered Mar 14 '26 00:03

Zaur Nasibov