Skip to content

Python文件处理

pure file

python
import os
import json
from pathlib import Path

def make_parents_dir(file_):
    file_path.parent.mkdir(parents=True, exist_ok=True)

def make_parents_dir(file_):
    dir_ = os.path.dirname(file_)
    if dir_ and not os.path.exists(dir_):
        os.makedirs(dir_)

def file_save_to_dest(data, filename):
    make_parents_dir(filename)
    with open(filename, 'wb') as file:
        file.write(data)
    print(f'[+] Saved {filename}')

def data_save_to_dest(data, filename):
    content = json.dumps(data, indent=2, ensure_ascii=False).encode()
    file_save_to_dest(content, filename)


# read and write binary content
def read_content(filename):
    with open(filename, 'rb') as fp:
        return fp.read()

def write_content(filename, content):
    with open(filename, 'wb') as fp:
        fp.write(content)

# read and write text
def read_file(filename):
    with open(filename, 'r', encoding='utf-8') as fp:
        return fp.read()

def write_file(filename, content):
    with open(filename, 'w', encoding='utf-8') as fp:
        fp.write(content)

# write file with create parent dir
def write_file_x(filename, content):
    
    def make_parents_dir(file_):
        dir_ = os.path.dirname(file_)
        if dir_ and not os.path.exists(dir_):
            os.makedirs(dir_)

    make_parents_dir(filename)
    with open(filename, 'w', encoding='utf-8') as fp:
        fp.write(content)

def read_lines(filename):
    return read_file(filename).strip().splitlines()

json

python
import json

def read_json_file(filename):
    with open(filename, 'r', encoding='utf-8') as fp:
        return json.load(fp)
    
def write_json_file(filename, data):
    with open(filename, 'w', encoding='utf-8') as fp:
        return json.dump(data, fp)

def write_json_file_pretty(filename, data):
    with open(filename, 'w', encoding='utf-8') as fp:
        return json.dump(data, fp, ensure_ascii=False, indent=2)

Released under the MIT License.