検索
ホームページバックエンド開発Python チュートリアルPythonのos.pathパスモジュールの操作方法まとめ

解析路径
路径解析依赖与os中定义的一些变量:

  • os.sep-路径各部分之间的分隔符。
  • os.extsep-文件名与文件扩展名之间的分隔符。
  • os.pardir-路径中表示目录树上一级的部分。
  • os.curdir-路径中当前目录的部分。

split()函数将路径分解为两个单独的部分,并返回包含这些结果的tuple。第二个元素是路径的最后部分,地一个元素是其他部分。

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

输入参数以os.sep结尾时,最后一个元素是空串。

输出:

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

basename()函数返回的值等价与split()值的第二部分。

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

整个路径会剥除到只剩下最后一个元素。

输出:

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

dirname()函数返回分解路径得到的第一部分。

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

将basename()与dirname()结合,得到原来的路径。

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

splitext()作用类似与split(),不过它会根据扩展名分隔符而不是目录分隔符来分解路径。import os.path

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

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

查找扩展名时,只使用os.extsep的最后一次出现。

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

commonprefix()取一个路径列表作为参数,返回一个字符串,表示所有路径中出现的公共前缀。

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

建立路径
除了分解现有路径外,还需要从其他字符串建立路径,使用join()。

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

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

如果要连接的某个参数以os.sep开头,前面所有参数都会丢弃,参数会返回值的开始部分。

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

规范化路径
使用join()或利用嵌入变量由单独的字符串组合路径时,得到的路径最后可能会有多余的分隔符或者相对路径部分,使用normpath()可以清除这些内容。

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

可以计算并压缩有os.curdir和os.pardir构成的路径段。

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

要把一个相对路径转换为一个绝对文件名,可以使用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))

结果是从一个文件系统树最顶层开始的完整路径。

          . : 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

文件时间

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__)

返回访问时间,修改时间,创建时间,文件中的数据量。

测试文件
程序遇到一个路径名,通常需要知道这个路径的一些信息。

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

遍历一个目录树

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)')

会生成一个递归的目录列表。

example (User data)
one/

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

一些实际的用法合集:

#创建文件:
os.mknod("test.txt")    创建空文件
fp = open("test.txt",w)   直接打开一个文件,如果文件不存在则创建文件
 
#获取扩展名:
>>> 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' 
 
#获取文件夹大小(Python3.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')

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Python vs. C:比較されたアプリケーションとユースケースPython vs. C:比較されたアプリケーションとユースケースApr 12, 2025 am 12:01 AM

Pythonは、データサイエンス、Web開発、自動化タスクに適していますが、Cはシステムプログラミング、ゲーム開発、組み込みシステムに適しています。 Pythonは、そのシンプルさと強力なエコシステムで知られていますが、Cは高性能および基礎となる制御機能で知られています。

2時間のPython計画:現実的なアプローチ2時間のPython計画:現実的なアプローチApr 11, 2025 am 12:04 AM

2時間以内にPythonの基本的なプログラミングの概念とスキルを学ぶことができます。 1.変数とデータ型、2。マスターコントロールフロー(条件付きステートメントとループ)、3。機能の定義と使用を理解する4。

Python:主要なアプリケーションの調査Python:主要なアプリケーションの調査Apr 10, 2025 am 09:41 AM

Pythonは、Web開発、データサイエンス、機械学習、自動化、スクリプトの分野で広く使用されています。 1)Web開発では、DjangoおよびFlask Frameworksが開発プロセスを簡素化します。 2)データサイエンスと機械学習の分野では、Numpy、Pandas、Scikit-Learn、Tensorflowライブラリが強力なサポートを提供します。 3)自動化とスクリプトの観点から、Pythonは自動テストやシステム管理などのタスクに適しています。

2時間でどのくらいのPythonを学ぶことができますか?2時間でどのくらいのPythonを学ぶことができますか?Apr 09, 2025 pm 04:33 PM

2時間以内にPythonの基本を学ぶことができます。 1。変数とデータ型を学習します。2。ステートメントやループの場合などのマスター制御構造、3。関数の定義と使用を理解します。これらは、簡単なPythonプログラムの作成を開始するのに役立ちます。

プロジェクトの基本と問題駆動型の方法で10時間以内にコンピューター初心者プログラミングの基本を教える方法は?プロジェクトの基本と問題駆動型の方法で10時間以内にコンピューター初心者プログラミングの基本を教える方法は?Apr 02, 2025 am 07:18 AM

10時間以内にコンピューター初心者プログラミングの基本を教える方法は?コンピューター初心者にプログラミングの知識を教えるのに10時間しかない場合、何を教えることを選びますか...

中間の読書にどこでもfiddlerを使用するときにブラウザによって検出されないようにするにはどうすればよいですか?中間の読書にどこでもfiddlerを使用するときにブラウザによって検出されないようにするにはどうすればよいですか?Apr 02, 2025 am 07:15 AM

fiddlereveryversings for the-middleの測定値を使用するときに検出されないようにする方法

Python 3.6にピクルスファイルをロードするときに「__Builtin__」モジュールが見つからない場合はどうすればよいですか?Python 3.6にピクルスファイルをロードするときに「__Builtin__」モジュールが見つからない場合はどうすればよいですか?Apr 02, 2025 am 07:12 AM

Python 3.6のピクルスファイルのロードレポートエラー:modulenotFounderror:nomodulenamed ...

風光明媚なスポットコメント分析におけるJieba Wordセグメンテーションの精度を改善する方法は?風光明媚なスポットコメント分析におけるJieba Wordセグメンテーションの精度を改善する方法は?Apr 02, 2025 am 07:09 AM

風光明媚なスポットコメント分析におけるJieba Wordセグメンテーションの問題を解決する方法は?風光明媚なスポットコメントと分析を行っているとき、私たちはしばしばJieba Wordセグメンテーションツールを使用してテキストを処理します...

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

DVWA

DVWA

Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser は、オンライン試験を安全に受験するための安全なブラウザ環境です。このソフトウェアは、あらゆるコンピュータを安全なワークステーションに変えます。あらゆるユーティリティへのアクセスを制御し、学生が無許可のリソースを使用するのを防ぎます。