解析路径
路径解析依赖与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')

Python은 데이터 과학, 웹 개발 및 자동화 작업에 적합한 반면 C는 시스템 프로그래밍, 게임 개발 및 임베디드 시스템에 적합합니다. Python은 단순성과 강력한 생태계로 유명하며 C는 고성능 및 기본 제어 기능으로 유명합니다.

2 시간 이내에 Python의 기본 프로그래밍 개념과 기술을 배울 수 있습니다. 1. 변수 및 데이터 유형을 배우기, 2. 마스터 제어 흐름 (조건부 명세서 및 루프), 3. 기능의 정의 및 사용을 이해하십시오. 4. 간단한 예제 및 코드 스 니펫을 통해 Python 프로그래밍을 신속하게 시작하십시오.

Python은 웹 개발, 데이터 과학, 기계 학습, 자동화 및 스크립팅 분야에서 널리 사용됩니다. 1) 웹 개발에서 Django 및 Flask 프레임 워크는 개발 프로세스를 단순화합니다. 2) 데이터 과학 및 기계 학습 분야에서 Numpy, Pandas, Scikit-Learn 및 Tensorflow 라이브러리는 강력한 지원을 제공합니다. 3) 자동화 및 스크립팅 측면에서 Python은 자동화 된 테스트 및 시스템 관리와 같은 작업에 적합합니다.

2 시간 이내에 파이썬의 기본 사항을 배울 수 있습니다. 1. 변수 및 데이터 유형을 배우십시오. 이를 통해 간단한 파이썬 프로그램 작성을 시작하는 데 도움이됩니다.

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...

Python 3.6에 피클 파일로드 3.6 환경 보고서 오류 : modulenotfounderror : nomodulename ...

경치 좋은 스팟 댓글 분석에서 Jieba Word 세분화 문제를 해결하는 방법은 무엇입니까? 경치가 좋은 스팟 댓글 및 분석을 수행 할 때 종종 Jieba Word 세분화 도구를 사용하여 텍스트를 처리합니다 ...


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

WebStorm Mac 버전
유용한 JavaScript 개발 도구

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기
