Python 擷取目錄下的檔案清單與內容__Python

來源:互聯網
上載者:User

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  該檔案是目錄形式
例子
例子  該檔案是目錄形式

 

 

 

 

 

 

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.