文件的基本读写
- path = r'C:\Users\Brady\Documents\tmp'
- 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 默认使用 \ r\n 做为换行符. 而类 unix 系统使用 \ n 作为换行符.
关于换行符的使用, 文档给出了如下解释:
如果 newline 为 None, 则 \ r \n \r\n 都会被识别为换行符, 并统一翻译为 \ n.
如果 newline 为'', 则直接返回源文件中的换行符
关于换行符 \ r\n 和 \ n 的历史要追溯到计算机出现之前的电传打印机. \r 的意思代表回车, 也就是打印头回到初始位置. \n 的意思表示换行, 也就是纸张往上卷一行. 在 Windows 中保留了这种老传统. 真正的换行符需要 \ r\n 而类 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'd\bak')
- shutil.copytree(src,dst)
这里需要注意的是, 目标目录不能是已存在的目录. 而且在复制的时候, 不带原目标目录的父目录. 说人话就是上面这段代码在执行的时候, 只会讲 c 目录内的内容复制到 bak 目录里去.
移动文件和目录
- import os
- import shutil
- src = os.path.join(basepath,'c')
- dst = os.path.join(basepath,r'd\bak')
- 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'.\d\backup','tar',r'.\d')
- shutil.unpack_archive(r'.\d\backup.tar')
吾码 2016
来源: https://www.cnblogs.com/thecatcher/p/12402480.html