欢迎访问宙启技术站
智能推送

10个Python文件处理函数

发布时间:2023-06-15 17:48:47

1. 文件读取函数:读取文本文件里的内容并返回字符串或列表

def read_file(file_path):

    with open(file_path, "r") as f:

        content = f.read()

    return content

2. 文件写入函数:将一个字符串或列表写入到指定文件中

def write_file(file_path, content):

    with open(file_path, "w") as f:

        f.write(content)

3. 文件判断函数:判断指定的文件是否存在

import os

def is_file_exists(file_path):

    return os.path.exists(file_path)

4. 文本替换函数:将文本文件里的某个字符或字符串替换为另一个字符或字符串

def replace_text(file_path, old_word, new_word):

    with open(file_path, "r") as f:

        content = f.read()

    new_content = content.replace(old_word, new_word)

    with open(file_path, "w") as f:

        f.write(new_content)

5. 文件移动函数:将一个文件从一个位置移动到另一个位置

def move_file(old_path, new_path):

    os.rename(old_path, new_path)

6. 文件复制函数:将一个文件复制到另一个位置

import shutil

def copy_file(src_path, dest_path):

    shutil.copy(src_path, dest_path)

7. 文件追加函数:将一个字符串或列表添加到文件的末尾

def append_file(file_path, content):

    with open(file_path, "a") as f:

        f.write(content)

8. 文件重命名函数:将文件重命名为另一个名称

import os

def rename_file(old_name, new_name):

    os.rename(old_name, new_name)

9. 删除文件函数:删除指定的文件

import os

def remove_file(file_path):

    os.remove(file_path)

10. 文件统计函数:统计文本文件的字符数、单词数、行数

def count_file(file_path):

    with open(file_path, "r") as f:

        content = f.read()

    num_chars = len(content)

    num_words = len(content.split())

    num_lines = content.count("

")

    return {"num_chars": num_chars, "num_words": num_words, "num_lines": num_lines}