我製作了一個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>
爲什麼你要定義一個函數print_result,該函數絕對不會打印?只需'print(name)'而不是'print_result()'。你有沒有看過任何教程或文件I/O文件?他們都會幫助你完成這項基本任務。 – TigerhawkT3