最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python中的os.path路徑模塊中的操作方法總結(jié)

 更新時(shí)間:2016年07月07日 17:20:59   作者:lucifercn  
os.path模塊主要集成了針對(duì)路徑文件夾的操作功能,這里我們就來看一下Python中的os.path路徑模塊中的操作方法總結(jié),需要的朋友可以參考下

解析路徑
路徑解析依賴與os中定義的一些變量:

  • os.sep-路徑各部分之間的分隔符。
  • os.extsep-文件名與文件擴(kuò)展名之間的分隔符。
  • os.pardir-路徑中表示目錄樹上一級(jí)的部分。
  • os.curdir-路徑中當(dāng)前目錄的部分。

split()函數(shù)將路徑分解為兩個(gè)單獨(dú)的部分,并返回包含這些結(jié)果的tuple。第二個(gè)元素是路徑的最后部分,地一個(gè)元素是其他部分。

import os.path
for path in [ '/one/two/three',
        '/one/two/three/',
        '/',
        '.',
        '']:
  print '%15s : %s' % (path, os.path.split(path))

輸入?yún)?shù)以os.sep結(jié)尾時(shí),最后一個(gè)元素是空串。

輸出:

 /one/two/three : ('/one/two', 'three')
/one/two/three/ : ('/one/two/three', '')
       / : ('/', '')
       . : ('', '.')
        : ('', '')

basename()函數(shù)返回的值等價(jià)與split()值的第二部分。

import os.path
for path in [ '/one/two/three',
        '/one/two/three/',
        '/',
        '.',
        '']:
  print '%15s : %s' % (path, os.path.basename(path))

整個(gè)路徑會(huì)剝除到只剩下最后一個(gè)元素。

輸出:

 /one/two/three : three
/one/two/three/ : 
       / : 
       . : .
        : 

dirname()函數(shù)返回分解路徑得到的第一部分。

import os.path
for path in [ '/one/two/three',
        '/one/two/three/',
        '/',
        '.',
        '']:
  print '%15s : %s' % (path, os.path.dirname(path))

將basename()與dirname()結(jié)合,得到原來的路徑。

 /one/two/three : /one/two
/one/two/three/ : /one/two/three
       / : /
       . : 
        : 

splitext()作用類似與split(),不過它會(huì)根據(jù)擴(kuò)展名分隔符而不是目錄分隔符來分解路徑。import os.path

for path in [ '/one.txt',
        '/one/two/three.txt',
        '/',
        '.',
        ''
        'two.tar.gz']:

  print '%21s : %s' % (path, os.path.splitext(path))

查找擴(kuò)展名時(shí),只使用os.extsep的最后一次出現(xiàn)。

       /one.txt : ('/one', '.txt')
  /one/two/three.txt : ('/one/two/three', '.txt')
          / : ('/', '')
          . : ('.', '')
      two.tar.gz : ('two.tar', '.gz')

commonprefix()取一個(gè)路徑列表作為參數(shù),返回一個(gè)字符串,表示所有路徑中出現(xiàn)的公共前綴。

import os.path
paths = [ '/one/two/three',
      '/one/two/threetxt',
      '/one/two/three/four',]
for path in paths:
  print 'PATH:', path

print
print 'PREFIX:', os.path.commonprefix(paths)

輸出:

PATH: /one/two/three
PATH: /one/two/threetxt
PATH: /one/two/three/four

PREFIX: /one/two/three

建立路徑
除了分解現(xiàn)有路徑外,還需要從其他字符串建立路徑,使用join()。

import os.path
for parts in [ ('one', 'two', 'three'),
      ('\one', 'two', 'three'),
      ('/one', '/two', '/three', '/four'),]:

  print parts, ':', os.path.join(*parts)

如果要連接的某個(gè)參數(shù)以os.sep開頭,前面所有參數(shù)都會(huì)丟棄,參數(shù)會(huì)返回值的開始部分。

('one', 'two', 'three') : one\two\three
('\\one', 'two', 'three') : \one\two\three
('/one', '/two', '/three', '/four') : /four

規(guī)范化路徑
使用join()或利用嵌入變量由單獨(dú)的字符串組合路徑時(shí),得到的路徑最后可能會(huì)有多余的分隔符或者相對(duì)路徑部分,使用normpath()可以清除這些內(nèi)容。

import os.path
for path in [ 'one/two/three',
       'one/./two/three',
       'one/../alt/two/three',
       ]:
  print '%20s : %s' % (path, os.path.normpath(path))

可以計(jì)算并壓縮有os.curdir和os.pardir構(gòu)成的路徑段。

    one/two/three : one\two\three
   one/./two/three : one\two\three
one/../alt/two/three : alt\two\three

要把一個(gè)相對(duì)路徑轉(zhuǎn)換為一個(gè)絕對(duì)文件名,可以使用abspath()。

import os.path
for path in [ '.',
       '..',
       'one/two/three',
       'one/./two/three',
       'one/../alt/two/three',
       ]:
  print '%20s : %s' % (path, os.path.abspath(path))

結(jié)果是從一個(gè)文件系統(tǒng)樹最頂層開始的完整路徑。

          . : C:\Users\Administrator\Desktop
         .. : C:\Users\Administrator
    one/two/three : C:\Users\Administrator\Desktop\one\two\three
   one/./two/three : C:\Users\Administrator\Desktop\one\two\three
one/../alt/two/three : C:\Users\Administrator\Desktop\alt\two\three

文件時(shí)間

import os
import time
print 'File:', __file__
print 'Access time:', time.ctime(os.path.getatime(__file__))
print 'Modified time:', time.ctime(os.path.getmtime(__file__))
print 'Change time:', time.ctime(os.path.getctime(__time__))
print 'Size:', os.path.getsize(__file__)

返回訪問時(shí)間,修改時(shí)間,創(chuàng)建時(shí)間,文件中的數(shù)據(jù)量。

測試文件
程序遇到一個(gè)路徑名,通常需要知道這個(gè)路徑的一些信息。

import os.path
filename = r'C:\Users\Administrator\Desktop\tmp'
print 'File    :', filename
print 'Is file?   :', os.path.isfile(filename)
print 'Absoulute  :', os.path.isabs(filename)
print 'Is dir?   :', os.path.isdir(filename)
print 'Is link?   :', os.path.islink(filename)
print 'Mountpoint? :', os.path.ismount(filename)
print 'Exists?    :', os.path.exists(filename)
print 'Link Exists? :', os.path.lexists(filename)

所有測試都返回布爾值。

File    : C:\Users\Administrator\Desktop\tmp
Is file?   : False
Absoulute  : True
Is dir?   : True
Is link?   : False
Mountpoint? : False
Exists?    : True
Link Exists? : True

遍歷一個(gè)目錄樹

import os
import os.path
import pprint
def visit(arg, dirname, names):
  print dirname, arg
  for name in names:
    subname = os.path.join(dirname, name)
    if os.path.isdir(subname):
      print '%s/' % name 
    else:
      print ' %s' % name
  print
if not os.path.exists('example'):
  os.mkdir('example')
if not os.path.exists('example/one'):
  os.mkdir('example/one')
with open('example/one/file.txt', 'wt') as f:
  f.write('i love you')
with open('example/one/another.txt', 'wt') as f:
  f.write('i love you, two')
os.path.walk('example', visit, '(User data)')

會(huì)生成一個(gè)遞歸的目錄列表。

example (User data)
one/

example\one (User data)
 another.txt
 file.txt

一些實(shí)際的用法合集:

#創(chuàng)建文件:
os.mknod("test.txt")    創(chuàng)建空文件
fp = open("test.txt",w)   直接打開一個(gè)文件,如果文件不存在則創(chuàng)建文件
 
#獲取擴(kuò)展名:
>>> os.path.splitext('/Volumes/Leopard/Users/Caroline/Desktop/1.mp4')[1:]
('.mp4',)
>>> os.path.splitext('/Volumes/Leopard/Users/Caroline/Desktop/1.mp4')[1]
'.mp4'
 
#獲取文件名:
>>> print os.path.basename(r'/root/hahaha/123.txt')
123.txt
>>> print os.path.dirname(r'/root/hahaha/123.txt')
/root/hahaha
 
#判斷目錄或文件的存在:
>>> os.path.exists('/root/1.py')
True
>>> os.path.exists('/root/')
True
>>> os.path.exists('/root')
True
>>> os.path.isdir('/root')
True
 
#改變工作目錄:
>>> os.chdir('/home')
>>> os.getcwd()
'/home'
 
#字符串分割:
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']
 
#獲取文件夾大小(Python2.x):
import os 
from os.path import join, getsize 
  
def getdirsize(dir): 
  size = 0L 
  for root, dirs, files in os.walk(dir): 
   size += sum([getsize(join(root, name)) for name in files]) 
  return size 
  
if __name__ == '__main__':
  filesize = getdirsize('/tmp') 
  print 'There are %.3f' % (filesize/1024/1024), 'Mbytes in /tmp' 
 
#獲取文件夾大?。≒ython3.x):
import os 
from os.path import join, getsize 
  
def getdirsize(dir): 
  size = 0 
  for root, dirs, files in os.walk(dir): 
   size += sum([getsize(join(root, name)) for name in files]) 
  return size 
  
if __name__ == '__main__':
  filesize = getdirsize('/tmp') 
  print ('There are ' + str(filesize/1024/1024) + 'Mbytes in /tmp')

相關(guān)文章

  • python字典取值的幾種方法總結(jié)

    python字典取值的幾種方法總結(jié)

    這篇文章主要介紹了python字典取值的幾種方法總結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-04-04
  • win10系統(tǒng)Anaconda和Pycharm的Tensorflow2.0之CPU和GPU版本安裝教程

    win10系統(tǒng)Anaconda和Pycharm的Tensorflow2.0之CPU和GPU版本安裝教程

    這篇文章主要介紹了win10系統(tǒng) Anaconda 和 Pycharm 的 Tensorflow2.0 之 CPU和 GPU 版本安裝教程,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-12-12
  • 對(duì)Python3中的print函數(shù)以及與python2的對(duì)比分析

    對(duì)Python3中的print函數(shù)以及與python2的對(duì)比分析

    下面小編就為大家分享一篇對(duì)Python3中的print函數(shù)以及與python2的對(duì)比分析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-05-05
  • pandas 讀取excel文件的操作代碼

    pandas 讀取excel文件的操作代碼

    pandas 讀取excel文件使用的是 read_excel方法。本文將詳細(xì)解析read_excel方法的常用參數(shù),以及實(shí)際的使用示例,感興趣的朋友跟隨小編一起看看吧
    2021-10-10
  • python如何操作mysql

    python如何操作mysql

    這篇文章主要介紹了python如何操作MySQL,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下
    2020-08-08
  • Python中type的構(gòu)造函數(shù)參數(shù)含義說明

    Python中type的構(gòu)造函數(shù)參數(shù)含義說明

    這篇文章主要介紹了Python中type的構(gòu)造函數(shù)參數(shù)含義說明,本文用一個(gè)編碼實(shí)例解釋Python type的參數(shù)的作用和含義,需要的朋友可以參考下
    2015-06-06
  • 如何基于線程池提升request模塊效率

    如何基于線程池提升request模塊效率

    這篇文章主要介紹了如何基于線程池提升request模塊效率,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-04-04
  • 在tensorflow實(shí)現(xiàn)直接讀取網(wǎng)絡(luò)的參數(shù)(weight and bias)的值

    在tensorflow實(shí)現(xiàn)直接讀取網(wǎng)絡(luò)的參數(shù)(weight and bias)的值

    這篇文章主要介紹了在tensorflow實(shí)現(xiàn)直接讀取網(wǎng)絡(luò)的參數(shù)(weight and bias)的值,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06
  • python異常觸發(fā)及自定義異常類解析

    python異常觸發(fā)及自定義異常類解析

    這篇文章主要介紹了python異常觸發(fā)及自定義異常類解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-08-08
  • python opencv 批量改變圖片的尺寸大小的方法

    python opencv 批量改變圖片的尺寸大小的方法

    這篇文章主要介紹了python opencv 批量改變圖片的尺寸大小的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-06-06

最新評(píng)論

东乡| 南郑县| 陕西省| 舞钢市| 湘西| 广德县| 涪陵区| 青海省| 建平县| 永安市| 含山县| 鸡东县| 右玉县| 哈巴河县| 禹州市| 巩义市| 商都县| 霍城县| 波密县| 西昌市| 宜春市| 航空| 中宁县| 长乐市| 施秉县| 河南省| 林口县| 谷城县| 兴城市| 南溪县| 怀宁县| 江孜县| 溧阳市| 老河口市| 黄龙县| 苏尼特左旗| 龙口市| 随州市| 会东县| 杭锦旗| 河北区|