Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.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_Loops_Directory_Writetofile - Fatal编程技术网

Python-文件列表,重复结果

Python-文件列表,重复结果,python,loops,directory,writetofile,Python,Loops,Directory,Writetofile,我是Python新手,正在尝试编写一个脚本来读取DIR并在.txt文件中返回该DIR 我的代码是: import os from os import walk rootdir = "C:\\PythonTesting\\dirReader\\test" fileslist = [] fileslisting=(fileslist) pathout=(rootdir+"\\output\\") #reqFileOutput=input("What do you want to call your

我是Python新手,正在尝试编写一个脚本来读取DIR并在.txt文件中返回该DIR

我的代码是:

import os
from os import walk
rootdir = "C:\\PythonTesting\\dirReader\\test"
fileslist = []
fileslisting=(fileslist)
pathout=(rootdir+"\\output\\")

#reqFileOutput=input("What do you want to call your output file.?")
reqFileOutput=("test") #temp file name for testing
OutputName=(reqFileOutput+".txt")

fileout = open(pathout+OutputName, "w") #wipes file if already exists
fileout.close()

def file_display(fileslist):
    print(fileslist)

    file=open(fileslist,"r")

    fileout = open(pathout+OutputName, "a")
    fileout.write(fileslist)


for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        filepath = subdir + os.sep + file
        if filepath.endswith(".txt"): 
            fileslist.append(filepath)
    for path in fileslist:
        file_display(path)    

input("\n\nExit?")
我有2个文件在我的目录与.txt TEST.txt和 TEST2.txt

当我运行这个脚本时,它会列出这些文件3次,但我不知道为什么? 接下来,我希望它将列表写入一个文本文件,当我这样做时,它只是将它们一个接一个地写入文件中,没有空格。
如何让它们列出?

看起来您的最后一个循环是缩进的,这意味着它包含在外部
for
循环中。因此,它将运行多次。请尝试此循环:

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        filepath = subdir + os.sep + file
        # collect paths to *.txt files found
        if filepath.endswith(".txt"): 
            fileslist.append(filepath)

# print paths to all *.txt files found
for path in fileslist:
    file_display(path)    

你的程序打印什么?您能显示输出文件的内容吗?您希望它是什么?我运行了您的代码,并且在输出中列出了3次路径,没有任何问题。您确定该路径中的文件不超过3个吗?我试过一个文件,两个文件,三个文件,效果很好。让它在单独的行上打印路径应该是一件简单的事情。还要完成退出提示的代码…请记住,它列出了您添加的2个文件和保存其他两个文件路径的测试文件…它将在文件夹中被视为另一个路径。谢谢,我仍然在了解缩进及其工作方式。我只使用Python大约一个月了。