Python 擷取目錄下的檔案清單與內容
下面的python例子是列舉使用者目錄下面的檔案
import os
import sys
#info=os.getcwd()
#listfile=os.listdir(os.getcwd())
info=raw_input("請輸入要列舉檔案的目錄:(如D:\\temp)")
listfile=os.listdir(info)
filename=open(info+'file.txt','w')
print listfile
#out=open(listfile,'r')
for line in listfile: #把目錄下的檔案都賦值給line這個參數
print line #列印出賦值的內容
#filename.write(filename)
if line[-3:] == '.py' or line[-4:] == '.txt':
print line
out=open(line,'r') #定義讀取line裡面的內容,也就是讀取每個檔案的內容
for com in out: #把每個檔案的內容(也就是目錄下的檔案)賦值給com
filename.write(line+": " +com)
else:
print (line+' '+"該檔案是目錄形式")
filename.close()
運行後的例子:
>>> import os
>>> import sys
>>> info=raw_input("請輸入要列舉檔案的目錄:")
請輸入要列舉檔案的目錄:C:\Python27\ //寫入的檔案目錄名
>>> listfile=os.listdir(info) //尋找目錄下所有的檔案
>>> filename=open(info+'file.txt','w')
>>> print listfile
['carddata.txt', 'DLLs', 'Doc', 'etc', 'file.txt', 'hhga.txt', 'include', 'Lib', 'libs', 'LICENSE.txt', 'ml.txt', 'myFile', 'NEWS.txt', 'numbers', 'python.exe', 'pythonw.exe', 'pywin32-wininst.log', 'README.txt', 'Removepywin32.exe', 'sample.csv', 'samples', 'Scripts', 'tcl', 'temp.py', 'test', 'tmp', 'Tools', 'unicode.txt', 'w9xpopen.exe', '\xc0\xfd\xd7\xd3']
>>> for line in listfile:
print line
if line[-3:] == '.py' or line[-4:] == '.txt':
print line
out=open(line,'r')
for com in out:
filename.write(line+": " +com) //向file.txt檔案裡寫入可讀檔案“.txt”每一行內容
else:
print (line+' '+"該檔案是目錄形式")
carddata.txt
carddata.txt
DLLs
DLLs 該檔案是目錄形式
Doc
Doc 該檔案是目錄形式
etc
etc 該檔案是目錄形式
file.txt
file.txt
hhga.txt
hhga.txt
include
include 該檔案是目錄形式
Lib
Lib 該檔案是目錄形式
libs
libs 該檔案是目錄形式
LICENSE.txt
LICENSE.txt
ml.txt
ml.txt
myFile
myFile 該檔案是目錄形式
NEWS.txt
NEWS.txt
numbers
numbers 該檔案是目錄形式
python.exe
python.exe 該檔案是目錄形式
pythonw.exe
pythonw.exe 該檔案是目錄形式
pywin32-wininst.log
pywin32-wininst.log 該檔案是目錄形式
README.txt
README.txt
Removepywin32.exe
Removepywin32.exe 該檔案是目錄形式
sample.csv
sample.csv 該檔案是目錄形式
samples
samples 該檔案是目錄形式
Scripts
Scripts 該檔案是目錄形式
tcl
tcl 該檔案是目錄形式
temp.py
temp.py
test
test 該檔案是目錄形式
tmp
tmp 該檔案是目錄形式
Tools
Tools 該檔案是目錄形式
unicode.txt
unicode.txt
w9xpopen.exe
w9xpopen.exe 該檔案是目錄形式
例子
例子 該檔案是目錄形式