Python 常见文件操作

goallin / 2023-08-21 / 原文

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}")