超全!python的文件和目录操作总结
基于Blazor写一个简单的五子棋游戏
文件的基础读写
path = r'C:UsersBradyDocumentstmp'
with open(path + r'demo.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
open()函数
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.
open函数用于翻开一个文件,并返回文件句柄.
文件翻开的mode主要有以下几种体式格局:
mode | 寄义 |
---|---|
'r' | 读取(默许) |
'w' | 写入(会截断之前的文件内容) |
'x' | 写入(假如文件已存在会发生非常) |
'a' | 追加,将新内容写入到文件末端 |
'b' | 二进制形式 |
't' | 文本形式(默许) |
'+' | 更新,可读可写 |
这里关于newline做一个诠释. newline是换行符,windows体系的换行符和类unix体系的换行符是不一样的. windows默许运用rn
做为换行符. 而类unix体系运用n
作为换行符.
关于换行符的运用,文档给出了以下诠释:
-
假如newline为None,则
r
n
rn
都会被识别为换行符,并一致翻译为
n
. -
假如newline为'',则直接返回源文件中的换行符
关于换行符
rn
和n
的汗青要追溯到计算机涌现之前的电传打印机.r
的意义代表回车,也就是打印头回到初始位置.n
的意义示意换行,也就是纸张往上卷一行. 在windows中保留了这类老传统. 真正的换行符须要rn
而类unix中则挑选运用n
作为换行符
write()函数
with open(path+r'demo2.txt','w',encoding='utf-8') as f:
content = 'this is a demo for write function'
res=f.write(content)
print(res)
file对应的要领
-
file.close(): 封闭文件 -
file.flush():讲缓冲区的内容马上写入文件 -
file.readline():读取整行 -
file.readlines():按行读取,并返回列表.能够设定读取的字节数 -
file.seek()设置游标位置 -
file.tell()显式当前游标位置 -
file.truncate()截取文件
目次相干操纵
猎取目次列表
with os.scandir(path2) as entries:
for item in entries:
print(item.name)
scandir()
返回的是一个生成器.
一样也能够运用pathlib库.
enties = Path(path2)
for entry in enties.iterdir():
print(entry.name)
猎取目次下的文件
for entry in os.listdir(basepath):
if os.path.isfile(os.path.join(basepath,entry)):
print(entry)
with os.scandir(basepath) as entries:
for entry in entries:
if entry.is_file():
print(entry.name)
base_path = Path(basepath)
for entry in base_path.iterdir():
if entry.is_file():
print(entry.name)
base_path = Path(basepath)
files_in_basepath = (entry for entry in base_path.iterdir() if entry.is_file())
for item in files_in_basepath:
print(item.name)
以上四种方法都能够.
猎取子目次
for entry in os.listdir(basepath):
if os.path.isdir(os.path.join(basepath,entry)):
print(entry)
with os.scandir(basepath) as entries:
for entry in entries:
if entry.is_dir():
print(entry.name)
base_path = Path(basepath)
for entry in base_path.iterdir():
if entry.is_dir():
print(entry.name)
猎取文件属性
with os.scandir(basepath) as entries:
for entry in entries:
info = entry.stat()
print(entry.name,timestamp2datetime(info.st_mtime))
base_path = Path(basepath)
for entry in base_path.iterdir():
info = entry.stat()
print(entry.name,timestamp2datetime(info.st_mtime))
os.scandir()
返回一个os.dirEntry对象. os.dirEntry对象大概有以下属性和要领:
-
name:文件(目次)名 -
path:文件(目次)途径 -
is_file() -
is_dir() -
stat()返回一个stat_result对象.
而stat_result对象又有N多关于文件的属性,比方时刻戳相干的属性:
-
st_atime:近来接见时刻 -
st_mtime:近来修正时刻 -
st_ctime:建立时刻
建立目次
在os
和pathlib
的模块中都包括了建立目次的函数.
-
os.mkdir() 建立单个子目次 -
os.makedirs() 建立多个目次,包括中心目次 -
Pathlib.Path.mkdir() 建立单个或许多个目次
建立单个目次
os.chdir(basepath)
if not os.path.exists(os.path.join(basepath,'c')):
os.mkdir('c')
base_path = Path(basepath+r'd')
try:
base_path.mkdir()
except FileExistsError :
pass
经由过程os.mkdir()和Path.mkdir()都能够建立单个目次. 假如目次已存在,则会报FileExistsError
非常. 也能够运用exist_ok=True
参数来疏忽这个非常
建立多个目次
能够运用os.makedirs()
来建立包括中心目次在内的一切目次,相似mkdir -p
os.makedirs('2020/3/2')
也能够运用Path.mkdir()
要领来建立多层目次.只须要指定parents=True
比方
from pathlib import Path
p = Path('2018/10/05')
p.mkdir(parents=True, exist_ok=True)
文件名的形式婚配
运用字符串要领
python有一些内置的修正和操纵字符串的要领,在操纵文件名的时刻,能够先遍历拿到文件名,然后运用字符串的体式格局举行婚配.
for item in os.listdir(basepath):
if item.endswith('.txt'):
print(item)
运用fnmatch库
别的还能够运用fnmatch库,fnmatch库支撑类unix的通配符.
通配符 | 寄义 |
---|---|
* | 婚配一切字符 |
? | 婚配恣意一个字符 |
[seq] | 婚配一个序列 |
[!seq] | 婚配一个不包括seq的序列 |
import fnmatch
for item in os.listdir(basepath):
if fnmatch.fnmatch(item,"*.txt"):
print(item)
运用glob库
总的来说,glob库和fnmatch库差不多,然则glob库供应了递归功用,能够查询目次下子目次的文件名. glob.glob(pathname, *, recursive=False)
别的在pathlib中也供应了相似glob的要领.
总结:
函数 | 形貌 |
---|---|
startswith() | 是不是以一个特定的序列开头 |
endswith() | 是不是以一个特定的序列末端 |
dnmatch.fnmatch(filename,pattern) | 测试文件名是不是满足正则表达式 |
glob.glob() | 返回婚配的文件列表 |
pathlib.Path.glob() | 返回一个婚配该形式的生成器对象 |
遍历和处置惩罚文件
os.walk(top, topdown=True, onerror=None, followlinks=False)
os.chdir(basepath)
for dirpath,dirname,files in os.walk('.'):
print(f'found directory:{dirpath}')
for filename in files:
print(filename)
walk()要领返回一个三元组(dirpath,dirnames,filenames)
-
dirpath:当前目次的称号 -
dirnames:当前目次中子目次的列表 -
当前目次中文件的列表
建立暂时文件和目次
暂时文件和暂时目次就是程序运转时建立,在程序运转完毕之后会自动删除的文件和目次. 能够运用tempfile
模块来举行操纵.
from tempfile import TemporaryFile
from tempfile import TemporaryDirectory
fp = TemporaryFile('w+t')
fp.write('hello world')
fp.seek(0)
data = fp.read()
print(data)
fp.close()
with TemporaryFile('w+t',encoding='utf-8') as tf:
tf.write('hello world')
tf.seek(0)
print(tf.read())
tmp=''
with TemporaryDirectory() as tmpdir:
print("create a temp directory{0}".format(tmpdir))
tmp = tmpdir
print(os.path.exists(tmp))
print(os.path.exists(tmp))
暂时文件作为一个暂时的硬盘上的缓存,平常不须要定名. 然则假如须要运用带文件名的暂时文件时,能够运用tempfile.NamedTemporaryFile()
在windows平台下,暂时文件平常寄存在C:/TEMP
或许C:/TMP
. 其他平台上,平常寄存次序为/tmp
,/var/tmp
,/usr/tmp
假如以上途径都找不到的话,python会默许在当前目次中寄存暂时文件和暂时目次.
注重,
TemporaryFile()
等要领也是支撑with..in这类上下文管理器的.
删除文件和目次
删除文件
要删除单个文件有三种方法:pathlib.Path.unlink()
, os.remove()
另有 os.unlink()
要领
这里须要注重的是,os.remove()和os.unlink()没有什么区别. unlink是类unix体系中的初期叫法.
os.remove(os.path.join(basepath,'demo.txt'))
os.unlink(os.path.join(basepath,'demo2.txt'))
或许运用pathlink.Path.unlink()要领
from pathlib import Path
p = Path(basepath+r'1-demo.txt')
p.unlink()
注重,以上要领只能删除文件,假如删除的不是文件而是目次的话,会报IsADirectoryError
非常
删除目次或目次树
三个要领:
-
os.rmdir() -
pathlib.Path.rmdir() -
shutil.rmtree()
在os.rmdir()和pathlib.Path.rmdir()中,假如删除的黑白空目次,会报OSError非常.
os.rmdir(os.path.join(basepath,'a'))
p = Path(basepath+r'b')
p.rmdir()
假如想删除非空目次或许目次树的话,能够是用shutil.rmtree()要领
shutil.rmtree(os.path.join(basepath,'2020'))
复制,挪动和重定名文件和目次
这里我们要运用到shutil模块,shutil模块供应了相似shell的一些功用.
复制文件
import os
import shutil
src = os.path.join(basepath,'0-demo.txt')
dst = os.path.join(basepath,'c')
shutil.copy(src,dst)
这个不须要多讲了,相似cp敕令. 假如dst是文件,则掩盖原文件,假如dst是目次的话,则拷贝到该目次下.
copy()要领不会复制元数据. 假如要连文件信息等元数据一同复制的话,则须要运用copy2()要领.
复制目次
import os
import shutil
src = os.path.join(basepath,'c')
dst = os.path.join(basepath,r'dbak')
shutil.copytree(src,dst)
这里须要注重的是,目标目次不能是已存在的目次. 而且在复制的时刻,不带原目标目次的父目次. 说人话就是上面这段代码在实行的时刻,只会讲c目次内的内容复制到bak目次里去.
挪动文件和目次
import os
import shutil
src = os.path.join(basepath,'c')
dst = os.path.join(basepath,r'dbak')
shutil.move(src,dst)
跟shell中的mv用法一样一样一样的. 假如目标目次存在,则会将源目次挪动到目标目次中去. 假如目标目次不存在,那就是源目次的重定名.
重定名文件和目次
但是运用os模块中的rename()要领,也能够运用pathlib.Path.rename()要领.
os.chdir(basepath)
os.rename('3-demo.txt','demo3.txt')
p = Path('0-demo.txt')
p.rename('demo0.txt')
归档
所谓归档就是打包. 最常见的两种打包体式格局就是zip和tar.(嗯...不要说rar...)
读取zip文件
python供应了zipfile的内置模块用来处置惩罚zip文件.
import os
import zipfile
os.chdir(basepath)
with zipfile.ZipFile('d.zip','r') as zf:
filelist=zf.namelist()
bar_file_info = zf.getinfo('d/bak/0-demo.txt')
print(type(bar_file_info))
print(bar_file_info.file_size)
print(filelist)
提取zip文件
经由过程zipfile.extract()和zipfile.extractall()能够从zip文件中提取一个或多个文件.
with zipfile.ZipFile('d.zip','r') as zipobj:
zipobj.extract('d/bak/0-demo.txt')
zipobj.extractall(path=r'./zip/')
建立新的zip文件
直接运用write()要领就能够了.
file_list = []
for item in os.listdir():
if fnmatch.fnmatch(item,'*-demo.txt'):
file_list.append(item)
with zipfile.ZipFile('demo.zip','w') as zipobj:
for txt_file in file_list:
zipobj.write(txt_file)
tarfile库的操纵
tar文件在linux中比较经常使用,能够运用gzip,bzip2和lzma等紧缩要领举行紧缩. python一样内置了tarfile库用于处置惩罚tar文件.
file_list = []
for item in os.listdir():
if fnmatch.fnmatch(item,'*-demo.txt'):
file_list.append(item)
# 建立一个tar包
with tarfile.open('demo.tar.gz',mode='w:gz') as tf:
for file_name in file_list:
tf.add(file_name)
# 读取tar包
with tarfile.open('demo.tar.gz',mode='r:gz') as tf:
for member in tf.getmembers():
print(member.name)
# 解紧缩tar包
with tarfile.open('demo.tar.gz',mode='r:gz') as tf:
tf.extract('2-demo.txt',path=r'./d/demo')
tf.extractall(path=r'./d/extractall')
关于翻开形式的诠释,懒得翻译了.
mode | action |
---|---|
'r' or 'r:*' | Open for reading with transparent compression (recommended). |
'r:' | Open for reading exclusively without compression. |
'r:gz' | Open for reading with gzip compression. |
'r:bz2' | Open for reading with bzip2 compression. |
'r:xz' | Open for reading with lzma compression. |
'x' or 'x:' | Create a tarfile exclusively without compression. Raise an FileExistsError exception if it already exists. |
'x:gz' | Create a tarfile with gzip compression. Raise an FileExistsError exception if it already exists. |
'x:bz2' | Create a tarfile with bzip2 compression. Raise an FileExistsError exception if it already exists. |
'x:xz' | Create a tarfile with lzma compression. Raise an FileExistsError exception if it already exists. |
'a' or 'a:' | Open for appending with no compression. The file is created if it does not exist. |
'w' or 'w:' | Open for uncompressed writing. |
'w:gz' | Open for gzip compressed writing. |
'w:bz2' | Open for bzip2 compressed writing. |
'w:xz' | Open for lzma compressed writing. |
shutil库建立存档
shutil库的make_archive()要领一样能够建立归档. shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])
shutil.unpack_archive(filename[, extract_dir[, format]])
shutil.make_archive(r'.dbackup','tar',r'.d')
shutil.unpack_archive(r'.dbackup.tar')
吾码2016
使用EventBus + Redis发布订阅模式提升业务执行性能