【问题标题】:Python - Filelisting, duplicate resultsPython - 文件列表,重复结果
【发布时间】:2017-08-21 16:04:37
【问题描述】:

我是 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?")

我的 DIR 中有 2 个带有 .txt 的文件 TEST.txt 和 TEST2.txt

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

【问题讨论】:

  • 你的程序print是什么?你能显示你的输出文件的内容,以及你想要的吗?
  • 我运行了您的代码,并且输出列出了 3 次路径都没有问题。您确定该路径中的文件不超过 3 个吗?我尝试了一个文件,两个文件,三个文件,它工作正常。让它在不同的行上打印路径应该是一件简单的事情。还要完成退出提示的代码...请记住,它列出了您添加的 2 个文件和包含其他两个文件路径的测试文件...它将在文件夹中作为另一个路径显示。

标签: python loops directory writetofile


【解决方案1】:

看起来您的最后一个循环是缩进的,这意味着它包含在外部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)    

【讨论】:

  • 谢谢,我仍然对压痕及其工作原理有所了解。只使用 Python 大约一个月。
猜你喜欢
  • 2020-04-12
  • 2012-06-09
  • 2020-09-24
  • 1970-01-01
  • 2017-01-18
  • 2013-08-17
  • 2016-10-03
  • 2016-12-28
  • 1970-01-01
相关资源
最近更新 更多