1. 程式人生 > >python筆記(一)獲取當前目錄路徑和檔案(抄錄)

python筆記(一)獲取當前目錄路徑和檔案(抄錄)

一、獲取當前路徑

 

      1、使用sys.argv[0]

import sys
print sys.argv[0]
#輸出
#本地路徑

     

      2、os模組

複製程式碼
import  os
print os.getcwd() #獲取當前工作目錄路徑
print os.path.abspath('.') #獲取當前工作目錄路徑
print os.path.abspath('test.txt') #獲取當前目錄檔案下的工作目錄路徑
print os.path.abspath('..') #獲取當前工作的父目錄 !注意是父目錄路徑
print os.path.abspath(os.curdir) #獲取當前工作目錄路徑
複製程式碼

 

 

    3、改變當前目錄

         1) 使用: os.chdir(path)。

         比如, 如果當前目錄在 ‘E:’ 下面, 然後進入E 下面的files 檔案 可以使用 os.chdir(E:\files).

         之後,使用比如 test1 = open('file1.txt'),  開啟的檔案會是在這個 ‘E:\files’ 目錄下的檔案,而不是 'E' 下的檔案。

   

    4、組合路徑返回

         os.path.join('file1','file2','file3')

         合併得到路徑 file1/file2/file3

>>> print os.path.join('E:', 'file1', 'file2')
E:/file1/file2
>>> print os.path.join('/home', '/home/file1/', '/home/file1/file2/')
/home/file1/file2/

        no.2

複製程式碼
import os
root = os.getcwd()               #獲得當前路徑 /home/dir1
print root
#輸出
#/home/dir1

name = "file1"                    #定義檔名字  
print(os.path.join(root, name))   #合併路徑名字和檔名字,並列印
#輸出
#/home/dir1/file1
複製程式碼

      

 

二、獲得當前目錄下所有檔案

      1. os.walk() 用於在目錄樹種遊走輸出目錄中的檔名字,向上或下;

複製程式碼
語法
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])

引數: top -- 根目錄下的每一個資料夾(包含它自己), 產生3-元組 (dirpath, dirnames, filenames)【資料夾路徑,
資料夾名字, 檔名】。 topdown --可選,為True或者沒有指定, 一個目錄的的3-元組將比它的任何子資料夾的3-元組先產生 (目錄自上而下)。
如果topdown為 False, 一個目錄的3-元組將比它的任何子資料夾的3-元組後產生 (目錄自下而上)。 onerror -- 可選,是一個函式; 它呼叫時有一個引數, 一個OSError例項。報告這錯誤後,繼續walk,或者丟擲exception終止walk。 followlinks -- 設定為 true,則通過軟連結訪問目錄。
複製程式碼

    2.

複製程式碼
import os
root = os.getcwd()

def file_name(file_dir):
    for root, dirs, files in os.walk(file_dir):
        print "-----------"
        print root   #os.walk()所在目錄
        print dirs   #os.walk()所在目錄的所有目錄名
        print files   #os.walk()所在目錄的所有非目錄檔名
        print " "

file_name(root)
複製程式碼