[Python] Privately created & used small-scale functions (file operations, etc.)

It's a small story, but ...

Various operations are easy for python, and if you place the created module in the environment variable "PYTHONPATH" It is a convenient language when creating detailed scripts because it is easy to reuse.

In this article, about the functions that I create and use privately I will introduce it in addition to the memo (Since there are many ordinary things, I think there are many already mentioned ones)

File read / write operation

import codecs
def pfreadlines(filename,encoding=None,**args):
    with codecs.open(filename,Mode="r",encoding=encoding,**args) as f:
        ret = f.readlines()
    return ret

def pfwritelines(data,filename,encoding=None,**args):
    with codecs.open(filename,Mode="w",encoding=encoding,**args) as f:
        f.writelines(data)

You can write / read to a file by calling one of the above functions It seems that convenience will increase if you also create read / write according to the situation.

Multiple Replace operations

You can also use regular expressions, but when you don't have to go that far

def replace_all(src,new,*old):
	for i in old:
		src = src.replace(i,new)
	
	return src

It seems to be confused because the argument is the opposite of the original replace ...

Add a new element when the key is not found in the target dict

def dict_insert(src,key,value=True):
    if(src.get(key) == None):
        src[key] = value

This is useful when there are many operations like "when the target key cannot be found" (was)

in conclusion

If you have something like "This operation can be written like this" or "This library is so convenient that I recommend it" Please comment.

Recommended Posts

[Python] Privately created & used small-scale functions (file operations, etc.)
File operations in Python
[Python] File / directory operations
File operations in Python
Summary of python file operations
Python memo ① Folder and file operations
Python CGI file created on Windows
ORC, Parquet file operations in Python
Python --Symbols used when performing operations
[Python3] Understand the basics of file operations
Bucket / file operations (transfer / acquire / delete / read, etc.) to GCS by python Summary
Python functions
File operations
[Python] Summary of S3 file operations with boto3
Standard .py file used in Python trials (template)-2020
Astro: Python modules / functions often used for analysis