Python未能写入列表中的所有条目

2 投票
5 回答
572 浏览
提问于 2025-04-16 21:50

我正在学习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,它就只会给我打印最后一个条目。

提前谢谢你们,
Nils

5 个回答

2

你在循环的每次迭代中都在打开并覆盖文件的内容。

可以在调用open(path)时传入'a',这样就可以在文件末尾添加内容,或者干脆在循环外部打开文件,然后在循环外部关闭它。

3
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)

避免使用没有意义的单字符变量名。我没有动你的getfiles()函数。不过,我把filelist这两个名字改了,因为它们都是内置函数的名字,用这些名字会把它们隐藏起来。

你只需要打开文件一次,而不是每一行都打开一次。你在每次写入时都把文件内容清空了。使用with可以确保即使出现错误,文件也会被正确关闭。

补充一下:如果你不需要在写入之前打印出每一行,可以在with块里只写一行代码:fileHandle.writelines(getfiles(a))

4

join() 修正一下,比如:

'\n'.join(str(path) for path in list)

另外,请把 "list" 这个变量改个名字,因为 list 是 Python 里自带的一种数据类型。

撰写回答