keywords: Python, How to read and write unicode (UTF-8) files

How to read and write unicode (UTF-8) files

source:

import io
with io.open(filename,'r',encoding='utf8') as f:
    text = f.read()
# process Unicode text
with io.open(filename,'w',encoding='utf8') as f:
    f.write(text)

Origin:
https://www.tutorialspoint.com/How-to-read-and-write-unicode-UTF-8-files-in-Python

How to convert dict to string

source:

str(dict)
Convert a python dict to a string and back

source:

import json

# convert to string
input = json.dumps({'id': id })

# load to dict
my_dict = json.loads(input) 

https://stackoverflow.com/questions/4547274/convert-a-python-dict-to-a-string-and-back

List files in particular directory

e.g.:

 import os
 arr = os.listdir()
 print(arr)

 >>> ['$RECYCLE.BIN', 'work.txt', '3ebooks.txt', 'documents']

How do I list all files of a directory?
https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory

Create a directory

e.g.

import os
if not os.path.exists(directory):
    os.makedirs(directory)

How can I safely create a nested directory?
https://stackoverflow.com/questions/273192/how-can-i-safely-create-a-nested-directory

Remove a directory

If you want to delete the file

import os
os.remove("path_to_file")

but you can`t delete directory by using above code if you want to remove directory then use this

import os
os.rmdir("path_to_dir")

from above command, you can delete a directory if it’s empty if it’s not empty then you can use shutil module

import shutil
shutil.rmtree("path_to_dir")

All above method are Python way and if you know about your operating system that this method depends on OS all above method is not dependent

import os
os.system("rm -rf _path_to_dir")

How to remove a directory including all its files in python?
https://stackoverflow.com/questions/43756284/how-to-remove-a-directory-including-all-its-files-in-python

Exampel 2:

import shutil

shutil.rmtree('/folder_name', ignore_errors=True)

How do I remove/delete a folder that is not empty?
https://stackoverflow.com/questions/303200/how-do-i-remove-delete-a-folder-that-is-not-empty


There is always some madness in love. But there is also always some reason in madness. ― Friedrich Nietzsche