Python - 文件列表,重复结果
Python - Filelisting, duplicate results
我是 Python 的新手,正在尝试制作一个脚本来读取 .txt 文件中的 DIR 和 returns 该 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)
我是 Python 的新手,正在尝试制作一个脚本来读取 .txt 文件中的 DIR 和 returns 该 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)