1. 程式人生 > >使用python讀取指定目錄下的指定型別檔案

使用python讀取指定目錄下的指定型別檔案

準備工作:設定指定的路徑,使用os.listdir() 方法獲取路徑下所有的檔案

import os
path = "d:\\data"                           # 設定路徑
dirs = os.listdir(path)                    # 獲取指定路徑下的檔案

迴圈判斷:使用os.path.splitext()方法篩選出指定型別的檔案

for i in dirs:                             # 迴圈讀取路徑下的檔案並篩選輸出
    if os.path.splitext(i)[1] == ".csv"
: # 篩選csv檔案 print i # 輸出所有的csv檔案

案例展示:

# encoding: utf-8
import os

path = "d:\\data"                           # 設定路徑
dirs = os.listdir(path)                    # 獲取指定路徑下的檔案
for i in dirs:                             # 迴圈讀取路徑下的檔案並篩選輸出
    if os.path.splitext(i)[1
] == ".csv": # 篩選csv檔案 print i # 輸出所有的csv檔案

執行結果:

20160904.csv
20160911.csv
20160918.csv
20160925.csv
20161002.csv
20161009.csv

函式解釋:
os.listdir(path)

函式功能:返回一個列表,其中包含由path指定的目錄中的條目的名稱。 列表是任意順序的。它不包括特殊條目’.‘ 和’..‘,即使它們存在於目錄中。

import os, sys

path = "d:\\tmp\\"
dirs = os
.listdir( path ) for file in dirs: print (file)

執行結果:

Applicationdocs.docx
test.java
book.zip
foo.txt
Java Multiple Inheritance.html
Java Multiple Inheritance_files
java.ppt
ParallelPortViewer

os.path.splitext(path)

函式功能:分離檔名與副檔名;預設返回(fname,fextension)元組,可做切片操作

import os, sys
path = 'c:\\csv\\test.csv'
print os.path.splitext(path) 

執行結果:

('c:\\csv\\test', '.csv')