1. 程式人生 > >文件操作及理論

文件操作及理論

als 鏈接 解析 循環 gid 工作目錄 http with result

路徑操作模塊
3.4 版本之前
os.path 模塊
from os import path
from os import path

p = path.join("/etc","sysconfig","network")
print(1,type(p),p)
print(2,path.exists(p))
print(3,path.split(p)) # (head,tail)
print(4,path.abspath(".")) #當前目錄
p = path.join("F:/",p,"test.txt")

print(5,path.dirname(p)) #路徑名
print(6,path.basename(p))# 文件名
print(7,path.splitdrive(p))#(盤符跟路徑的元組)

1 <class ‘str‘> /etc\sysconfig\network
2 False
3 (‘/etc\sysconfig‘, ‘network‘)
4 D:\Learning\project\exercise
5 F:/etc\sysconfig\network
6 test.txt
7 (‘F:‘, ‘/etc\sysconfig\network\test.txt‘)

p1 = path.abspath(file

)
print(p1,path.basename(p1))
while p1 != path.dirname(p1): # 如果p1 != p1 的路徑名,繼續循環
p1 = path.dirname(p1)
print(p1,path.basename(p1))

D:\Learning\project\exercise\testfunc.py testfunc.py
D:\Learning\project\exercise exercise
D:\Learning\project project
D:\Learning Learning
D:\

3.4版本開始
建議使用pathlib模塊,提供Path對象來操作。包括目錄和文件

from pathlib import Path
p = Path() #當前目錄
p = Path("a","b","c/d")# 當前目錄下的a/b/c/d
p = Path("/etc")# 根下的etc目錄
絕對路徑:
p.absolute()
路徑拼接和分解
操作符 “/ ”

Path對象 / Path對象
Path對象 / 字符串 或者 字符串 / Path對象

分解
parts 屬性,可以返回路徑中的每一個部分
p1 = a\b\c\d\e\f
print(p1.parts)

(‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘)
jointpath
jointpath(*other)連接多個字符串到Path對象中
p = Path("a/b/c")
print(1,p)
p1 = p / "d" / "e" / "f"
print(2,p1)
print(3,p1.parts)
p3 = p.joinpath("a","b","c",p,p / "d",Path("http"))
print(4,p3)
print(5,p.joinpath("etc","init.d",Path("http")))
print(6,p)

1 a\b\c
2 a\b\c\d\e\f
3 (‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘)
4 a\b\c\a\b\c\a\b\c\a\b\c\d\http
5 a\b\c\etc\init.d\http
6 a\b\c

獲取路徑
str 獲取路徑字符串
bytes 獲取路徑字符串的bytes
p4 = Path("etc")
s = str(p4)
b = bytes(p4)
print(s,b)

etc b‘etc‘

全局方法
cwd() 返回當前工作目錄
home() 返回當前家目錄
判斷方法
p = Path("/etc/mysqlinstall/mysql.tar.gz")
print(p.is_dir()) #是否是目錄,目錄存在返回True
print(p.is_file()) #是否是普通文件,文件存在返回True
print(p.is_symlink())# 是否是軟鏈接
print(p.is_socket()) #是否是socket文件
print(p.is_block_device())#是否是塊設備
print(p.is_char_device())# 是否是字符設備
print(p.is_absolute()) #是否是絕對路徑
print(p.resolve()) #返回一個新的路徑,這個路徑就是當前Path對象的絕對路徑,如果是軟鏈接則直接被解析
print(p.exists()) #目錄或文件是否存在

False
False
False
False
False
False
False
D:\etc\mysqlinstall\mysql.tar.gz
False

rmdir() 刪除空目錄。沒有提供給判斷目錄為空的方法
目錄不為空時,彈出OS Error(OSError: [WinError 145] 目錄不是空的。: ‘F:\newfile‘)

touch(mode=0o666,exist_ok = True)創建一個文件

as_uri() 將路徑返回成URI,例如“file:///etc/passwd”
print(Path("F:/file/a/b/c/d").as_uri())

file:///F:/file/a/b/c/d

mkdir(mode=0o777,parents=False,exist_ok=False)
parents,是否創建父目錄,True等同於mkdir -p; False時,父目錄不存在,則拋出FileNotFoundError
exist_ok參數,在3.5版本加入。False時,路徑存在,拋出FileExistsError;True時,Error被忽略

iterdir() 叠代當前目錄 (沒有遞歸,當前目錄下的文件)
from pathlib import Path
p = Path("a/b/c/d/")
print(p.iterdir()) # 返回一個生成器對象

<generator object Path.iterdir at 0x0000020C28100830>

from pathlib import Path
p = Path("F:/newfile")
for y in p.parents[len(p.parents) - 1].iterdir():
print(y, end="\t")
if y.isdir():
flag = False
for
in y.iterdir():
flag = True
break
print("dir","not empty" if flag else "empty",sep="\t")
elif y.is_file():
print("file")
else:
print("other file")

py12-湖北-胡炎林 2018/9/9 17:36:46

通配符
glob(pattern) 通配給定的模式
rglob(pattern)通配給定的模式,遞歸目錄
都返回一個生成器
list(p.glob("test*")) #返回當前目錄對象下的test開頭的文件
list(p.glob("*/.py"))#遞歸所有目錄,等同rglob
g = p.rglob("*.py") #生成器
next(g)

匹配
match(pattern)
模式匹配,成功返回True
Path("a/b/.py").match("*.py") #True
Path("a/b/c.py").match("b/c.py") #True
Path("a/b/c.py").match("*/.py") #True

stat() 相當於stat命令
lstat() 同 stat() 但如果是符號鏈接,則顯示符號鏈接本身的文件信息
from pathlib import Path
import os
p = Path("F:/test.ini")
a = p.stat()
print(a)
b = os.stat(p)
print(b)

os.stat_result(st_mode=33206, st_ino=1970324836978426, st_dev=3024289130, st_nlink=1, st_uid=0, st_gid=0, st_size=209, st_atime=1536146816, st_mtime=1536146886, st_ctime=1536130661)
os.stat_result(st_mode=33206, st_ino=1970324836978426, st_dev=3024289130, st_nlink=1, st_uid=0, st_gid=0, st_size=209, st_atime=1536146816, st_mtime=1536146886, st_ctime=1536130661)

文件操作
Path.open(mode="r",buffer=-1,encoding=None,errors=None,newline=None)
使用方法類似內內建函數open。返回一個文件對象,3.5增加的新函數

Path.read_bytes()
以“rb”讀取路徑文件,並返回二進制流。
Open the file in text mode, read it, and close the file.

Path.read_text(encoding=None,error=None)
以“rt”讀取路徑對應文件,返回文本

Path.write_bytes(data)
以“wb”方式寫入數據到路徑對應文件

Path.write_text(data)
以“wt”方式寫入數據到路徑對應文件

open模式進行文件copy
src = "F:/test.txt"
dest = "F:/newfile/test1"
def copy_file(src,dest):
with open(src) as f1:
with open(dest,"w+") as f2:
f2.write(f1.read())

copy_file(src,dest)

父目錄
partent 目錄的邏輯父目錄
parents 父目錄序列,索引0是直接的父
p5 = Path("a/b/c/d/e")
print(1,p5.parent.parent)
for x in p5.parents:
print(2,x)

1 a\b\c
2 a\b\c\d
2 a\b\c
2 a\b
2 a
2 .

目錄組成部分:
name、stem、suffix、suffixes、with_suffix(suffix)、with_name(name)
name 目錄的最後一個部分
suffix 目錄中最後一個部分的擴展名
stem 目錄最後一個部分,沒有後綴
suffixes 返回多個擴展名列表
with_suffix(suffix)有擴展名則替換,無則補充擴展名
with_name(name)替換目錄最後一個部分並返回一個新的路徑
from pathlib import Path

p = Path("/etc/mysqlinstall/mysql.tar.gz")
print(1,p.name)
print(2,p.suffix)
print(3,p.suffixes)# 返回多個擴展名列表
print(4,p.stem)
print(5,p.with_suffix(".png"))
print(6,p.with_name("mysql.tgz"))
p = Path("README")
print(7,p.with_suffix(".txt"))
print(8,p.with_suffix(".txt").suffixes)

1 mysql.tar.gz
2 .gz
3 [‘.tar‘, ‘.gz‘]
4 mysql.tar
5 \etc\mysqlinstall\mysql.tar.png
6 \etc\mysqlinstall\mysql.tgz
7 README.txt
8 [‘.txt‘]

文件操作及理論