Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python没有';不要从列表中写入所有条目_Python_File_List_Join - Fatal编程技术网

Python没有';不要从列表中写入所有条目

Python没有';不要从列表中写入所有条目,python,file,list,join,Python,File,List,Join,我正在探索python,并尝试按last modified对目录中的所有文件进行排序,然后将列表写入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(ke

我正在探索python,并尝试按last modified对目录中的所有文件进行排序,然后将列表写入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”。加入它只会打印最后一个条目

提前感谢,,
Nils

在写入文件时执行以下操作:

fileHandle = open (file, 'w' )  
for listItem in list:
    print listItem    
    fileHandle.write (str(listItem) + "\n")
fileHandle.close()
更正
连接()
,例如:

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

请重命名“list”变量,因为
list
是Python中的内置数据类型

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


将“a”传递给
open(path)
调用以附加到文件,或者在循环外部将其打开一次,然后在循环外部将其关闭。

因为您将列表中的每个条目转换为
str
,所以连接会对每个条目进行操作
str
,因为它们也算作iterables,因此将
\n
放在 每个字符,而不是列表中的每个项目。将行更改为
fileHandle.write('\n'.join(str(path)表示列表中的路径))
将修复此问题,就像BasicWalf编写的一样

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()函数。但是,我确实重命名了
文件
列表
,因为这两个都是内置函数的名称,当您使用这些名称时,会将它们隐藏起来

您还只需要打开文件一次,而不是每行打开一次。每次写入时都会截断文件。将
一起使用可确保即使出现错误,文件句柄也会关闭


编辑:如果您不需要在写入前打印每一行,您可以在
块中的
中有一行:
fileHandle.writelines(getfiles(a))

请不要有像
list=[]
file='c://test.txt'
(特别是
列表
这样的行)。这些都是你不应该隐藏的东西。如果你想调用
list(some_iterable)
,那之后会发生什么呢?最好的答案是,它消除了
范围(len())
的混乱,改进了命名,并修复了这两个错误。它将条目写入到文件中而没有下一行。所以他们把我们堆在一起了。但总的来说,翻拍的比我的好