将文件名列表的输出打印到文本文件

问题描述:

我制作了一个Python程序,用于检查文件夹中的文件并返回以.txt结尾的文件列表。现在我想输出到一个文件。这里是我的代码:将文件名列表的输出打印到文本文件

import os 
import os.path 
import sys 

f=open("E:\\test.txt",'w') 
f.write('') 

path=os.path.abspath("E:\\test") 
def print_result(): 
    print(name) 
for root, dirs, files in os.walk(path): 
    for name in files: 
     if name.endswith(".txt"): 
      print_result() 

Version 1: 

alist=[print_name]    
alist.append(print_result) 
f=open("E:\\test.txt", 'a') 
f.writelines(alist) 

Version 2: 

alist=name 
alist.append(name) 
f = open("E:\\test.txt",'a') 
print (name) 

Version 3: 

frame=print_result 
saveout = sys.stdout 
fsock = open("E:\\test.txt", 'a') 
sys.stdout = fsock 
print (frame) 
sys.stdout = saveout`enter code here` 

As you can see i have tried diferent types. The thing is that i only get the following in the file, instead of the actual output list: 

<function print_result at 0x004F6DB0> 
+1

为什么你要定义一个函数print_result,该函数绝对不会打印?只需'print(name)'而不是'print_result()'。你有没有看过任何教程或文件I/O文件?他们都会帮助你完成这项基本任务。 – TigerhawkT3

的名称来访问,不仅* .txt文件在当前工作目录,而且在任何子目录,递归,这是我认为你试图实现与在os.walk()参考,请尝试以下操作:

import os 
def GetFiles(dir,f): 
    basedir = dir 
    subdirs = [] 
    for fname in os.listdir(dir): 
     fileName = os.path.join(basedir, fname) 
     if os.path.isfile(fileName): 
      if fileName.endswith(".txt"): 
       f.write(fileName+"\n") 
       print fileName 
     elif os.path.isdir(fileName): 
      subdirs.append(fileName) 
    for subdir in subdirs: 
     GetFiles(subdir,f) 
f=open("test.txt",'w') 
GetFiles('./',f) 
f.close() 

这将列出与当前工作目录及其所有子目录名为“.txt”结尾的文件,把路径和文件名的文件test.txt

这可以使用做了一些简单的一个glob

import glob 

txtfiles = glob.glob('E:\\test\\*.txt') 
with open('E:\\test.txt', 'w') as f: 
    for txtfile in txtfiles: 
     f.write('{}\n'.format(txtfile)) 
+0

谢谢。这工作! –

+1

我明白OP已经接受了这个方法,但原来的代码使用'os.walk()'所以使用'glob'不会产生相同的结果,因为它不会挖到子目录中。 –

+0

这是一个很好的观点。 –

你需要得到一个目录下的所有文件

假设你有一个目录路径为“/ home/ubuntu/test”,并且您想将结果写入文件“的结果。 TXT”

from os import listdir 
from os.path import isfile, join 

onlyfiles = [ f for f in listdir("/home/ubuntu/test") if isfile(join("/home/ubuntu/test",f)) ] 

with open ("/home/ubuntu/result.txt","w")as fp: 
    for line in onlyfiles: 
    fp.write(line+"\n") 

然后得“/家/ Ubuntu的/”和开放的Result.txt。您将自身的文件有