开发者

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


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.


import os, os.path

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

outfile='c://test.txt'

with open(outfile, 'w') as fileHandle:
    lines = getfiles(a)
    for line in lines:
        print line
        fileHandle.write(line)

Avoid using meaningless one character variable names. I also did not touch your getfiles() function. I did, however, rename file and list as those are both the names of built in functions, which you're hiding when you use those names.

You also only need to open the file once, not once per line. You were truncating the file on every write. Using with makes sure the file handle gets closed even if you have an error.

Edit: If you don't need to print out each line before writing it, you can just have one line inside the with block: fileHandle.writelines(getfiles(a)).


You are opening and overwriting the file contents in each iteration of the loop.

Pass 'a' to the open(path) call to append to the file, or simply open it once outside the loop and close it outside the loop.


Because you convert each entry in the list to str the join operates on each str because they also count as iterables and therefore a \n is put between each character, not every item in the list. Changing the line to fileHandle.write ('\n'.join(str(path) for path in list))) will fix this just like BasicWolf wrote.


Do this when writing the file:

fileHandle = open (file, 'w' )  
for listItem in list:
    print listItem    
    fileHandle.write (str(listItem) + "\n")
fileHandle.close()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜