python-3.xeasing

How to simplify the process of saving files in python


How to read and write files in python easier? By one line? What variants of function can be for:

with open(file='file_name', mode='r', encoding='utf8') as f:
    F = f.read()

Solution

  • Making it easier to read json

    # pip install varname
    def read_j(file_name, encod='utf8'):
        with open(file_name, 'r', encoding=encod) as f:
            F = json.load(f)
            return F
    

    Making it easier to write json

    def write_j(data, file_name=None, type_='w', indent=4, ensure_ascii=False, encod='utf8'):
        if file_name == None:
            file_name = varname.nameof(data, frame=2) + '.json'
    
        with open(file_name, type_, encoding=encod) as f:
            json.dump(data, f, indent=indent, ensure_ascii=ensure_ascii)
    

    Making it easier to read file

    def read_f(file_name, encod='utf8'):
        with open(file_name, 'r', encoding=encod) as f:
            F = f.read()
            return F
    

    Making it easier to write file

    def write_f(data, file_name=None, type_='w', encod='utf8'):
        # print(data)
        if file_name == None:
            file_name = varname.nameof(data, frame=2)
            if type(data) == list or type(data) == dict:
                write_j(data, file_name+'.json')
            elif type(data) == str:
                file_name = file_name + '.txt'
                with open(file_name, type_, encoding=encod) as f:
                    f.write(data)
            elif type(data) == bytes:
                with open(file_name, mode='wb', encoding=None) as f:
                    f.write(data)
        else:
            with open(file_name, type_, encoding=encod) as f:
                f.write(data)