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

时间:2015-10-17 09:01:38

标签: python

我制作了一个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>

3 个答案:

答案 0 :(得分:0)

使用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))

答案 1 :(得分:0)

您需要获取目录中的所有文件

  

假设您有一个目录路径为&#34; / home / ubuntu / test&#34; ,并且您希望在文件&#34;结果中写入结果。 TXT&#34;

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")
  

然后到&#34; / home / ubuntu /&#34; 并打开 result.txt 。你将看到那里的文件名称

答案 2 :(得分:0)

不仅要访问当前工作目录中的* .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