# 遍历文件夹
import os
import tempfile
from importlib_metadata import files
def traverse(path):
for basepath, directories, files in os.walk(path):
for f in files:
yield os.path.join(basepath, f)
# for f in traverse("."):
# print(f)
# 路径处理
import pathlib
path = pathlib.Path('somefile.txt')
path.write_text('Hello World') # write some text into file.
print(path.resolve()) # print absolute path
path.read_text() # check the file content
path.unlink() # destroy the file
# 斜杠 / 操作符有助于创建子路径,就像 os.path.join() 一样
path = pathlib.Path('.')
path = path.resolve()
print(path)
path = path / '..'
print(path.resolve())
# 文件名扩展、通配
list(pathlib.Path('.').glob('*.py'))
list(pathlib.Path('.').glob('**/*.py'))
# 文件属性
pathlib.Path('toolscode/check_sth/test.py').stat()
# os.stat_result(st_mode=33206,
# st_ino=12947848929028083,
# st_dev=975173416,
# st_nlink=1,
# st_uid=0,
# st_gid=0,
# st_size=1048,
# st_atime=1644304359,
# st_mtime=1643187494,
# st_ctime=1643157922)
# 文件是否存在,是否文件夹
pathlib.Path("conf.py").exists()
pathlib.Path("conf.py").is_dir()
# 临时文件
from tempfile import NamedTemporaryFile
with NamedTemporaryFile() as f:
print(f.name)
os.system('echo "hello world" > %s' % f.name)
f.seek(0)
print(f.read())
# 超过缓存大小,转移到临时文件,以免撑爆内存
with tempfile.SpooledTemporaryFile(max_size=30) as temp:
for i in range(3):
temp.write(b'line of text\n')
print(temp._file)
temp.seek(0)
print(temp.read())
# 文件名编解码
import sys
def decode_filename(fname):
fse = sys.getfilesystemencoding()
return fname.decode(fse, "surrogateescape")
# 复制目录
import shutil
def copydir(source, dest, ignore=None):
"""Copy source to dest and ignore and file matching ignore pattern."""
shutil.copytree(source, dest, ignore_dangling_symlinks=True, ignore=shutil.ignore_patterns(*ignore) if ignore else None)
Python文件目录
于 2022-02-08 16:10:35 首次发布