Python文件目录


# 遍历文件夹
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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值