2015-10-17 201 views
0

我製作了一個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

回答

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

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)) 
+0

謝謝。這工作! –

+1

我明白OP已經接受了這個方法,但原來的代碼使用'os.walk()'所以使用'glob'不會產生相同的結果,因爲它不會挖到子目錄中。 –

+0

這是一個很好的觀點。 –

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。您將自身的文件有