Python 常见文件操作

本文详细介绍了Python中使用os,shutil和pathlib进行文件操作的方法,包括文件存在判断、删除、写入、读取、创建目录、复制、移动以及获取文件大小和修改时间等。

Python 常见文件操作

Python 常见的文件操作主要由 os, shutil, pathlib 等提供

import os
import shutil
import time
from pathlib import Path


def test_file():
    filename = "test_file.txt"
    # 判断文件是否存在
    if os.path.exists(filename):
        # 删除文件
        os.remove(filename)
    # 写文件
    with open("test_file.txt", "w") as file:
        file.write("hello python")
    # 读文件
    with open("test_file.txt", "r") as file:
        s = file.read()
        assert s == "hello python"

    # 创建文件夹
    if os.path.exists("test_file"):
        shutil.rmtree("test_file")
    os.mkdir("test_file")
    shutil.rmtree("test_file")

    # 创建多级文件夹
    Path("a/b/c").mkdir(parents=True, exist_ok=True)
    shutil.rmtree("a")

    # 复制文件
    copy_file = "test_file_copied.py"
    if os.path.exists(copy_file):
        os.remove(copy_file)
    shutil.copy("test_file.py", copy_file)
    assert os.path.exists(copy_file)
    os.remove(copy_file)

    # 移动文件
    move_file = "test_zip_mv.py"
    if os.path.exists(move_file):
        os.remove(move_file)
    shutil.move("test_zip.py", move_file)
    assert os.path.exists(move_file) and not os.path.exists("test_zip.py")
    shutil.move(move_file, "test_zip.py")

    # 文件大小,修改时间等
    file = Path("test_file.py")
    size = file.stat().st_size
    modify_time = time.ctime(file.stat().st_mtime)
    print(f"test_file.py size:{size}, modify_time:{modify_time}")
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值