Python基础之IO操作

Python基础之IO操作


本节代码包含Python中最基本的IO操作示例,包括读取文件,写文件,copy目录所有内容,列举目录,删除目录所有内容,修改文件名,修改目录等。

import os


def read_all(file_path):
    """
    Read all content of a file
    :param file_path: file path
    :return: All content of a file
    """
    with open(file_path, "r") as f:
        return f.read()


def read_lines(file_path):
    """
    Read a file line by line
    :param file_path: file path
    :return: All content of a file
    """
    content = ""
    with open(file_path, "r") as f:
        for line in f.readlines():
            content += line
    return content


def write_file(file_path):
    """
    Write content to a file, all content at a time
    :param file_path: file path
    :return: None
    """
    (path, name) = os.path.split(file_path)
    new_file_name = os.path.join(path, name + '.backup')
    with open(new_file_name, "w+") as f:
        f.write(read_all(file_path))


def write_file_chunk(file_path):
    """
    Write content to a file, chunk number content at a time
    :param file_path: file path
    :return: None
    """
    (path, name) = os.path.split(file_path)
    new_file_path = os.path.join(path, name + '.backup_chunk')
    with open(new_file_path, "wb") as f_out:
        with open(file_path, "rb") as f_in:
            while chunk := f_in.read(100):
                f_out.write(chunk)


def list_folder(folder):
    """
    List all files and sub folders in a folder
    :param folder: folder
    :return: None
    """
    print(folder)
    for file in os.listdir(folder):
        path = os.path.join(folder, file)
        if os.path.isdir(path):
            list_folder(path)
        else:
            print(path)


def list_foler_tree(folder):
    for root, dirs, files in os.walk(folder, topdown=False):
        print("-----------------")
        for f in files:
            print(os.path.join(root, f))
        for f in dirs:
            print(os.path.join(root, f))


def copy_file(src_file_path, dest_folder_path):
    """
    Copy src_path to dest_folder
    :param src_file_path: source file path
    :param dest_folder_path: dest folder
    :return: None
    """
    if not os.path.isdir(dest_folder_path):
        print("%s is not a folder." % dest_folder_path)
        return

    if not os.path.isfile(src_file_path):
        print("%s is not a file." % src_file_path)
        return

    file_name = os.path.basename(src_file_path)
    dest_file_path = os.path.join(dest_folder_path, file_name)
    with open(src_file_path, "rb") as f_in:
        with open(dest_file_path, "wb") as f_out:
            while chunk := f_in.read(1024 * 10):
                f_out.write(chunk)


def copy_folder(src_folder_path, dest_folder_path):
    """
    Copy src folder to a dest folder
    :param src_folder_path:
    :param dest_folder_path:
    :return:
    """
    if not os.path.isdir(src_folder_path):
        print("%s is not a folder." % src_folder_path)
        return

    if not os.path.isdir(dest_folder_path):
        print("%s is not a folder." % dest_folder_path)
        return

    dest_path = os.path.join(dest_folder_path, os.path.basename(src_folder_path))
    os.mkdir(dest_path)

    for file in os.listdir(src_folder_path):
        path = os.path.join(src_folder_path, file)
        if os.path.isdir(path):
            copy_folder(path, dest_path)
        else:
            copy_file(path, dest_path)


def remove_dirs(folder):
    """
    Remove a folder
    :param folder: folder path
    :return: None
    """
    for root, dirs, files in os.walk(folder, topdown=False):
        for name in files:
            os.remove(os.path.join(root, name))
        for name in dirs:
            os.rmdir(os.path.join(root, name))
    os.rmdir(folder)


def rename(file_path, new_file_path):
    """
    Used to rename a file or a folder
    :param file_path:
    :param new_file_path:
    :return:
    """
    if not os.path.exists(file_path):
        print("%s doesn't exist." % file_path)
        return
    os.rename(file_path, new_file_path)


def test():
    # print(read_all(__file__))
    # print(read_lines(__file__))
    # write_file(__file__)
    # write_file_chunk(__file__)
    # list_folder("D:\Docs\study\python")
    # copy_file("D:/Docs/study/python/00ubuntu安装教程.zip", "D:/work/python_workspace/basics")
    # copy_folder("D:\KuGou", "D:/work/python_workspace/basics")
    # os.remove("D:/work/python_workspace/basics/KuGou")
    # remove_dirs('D:/work/python_workspace/basics/KuGou')
    # list_foler_tree("D:\KuGou")
    # rename("D:/work/python_workspace/basics/io_operations.py.backup2", "D:/work/python_workspace/basics/io_operations.py.backup")
    rename("D:/work/python_workspace/basics/test", "D:/work/python_workspace/basics/test2")


if __name__ == '__main__':
    test()

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值