Frequently Used Python Commands¶
This post is about the Python commands I use or Google frequently.
To find the absolute path of the directory of the current file being executed -
[4]:
import os
abs_path = os.path.dirname(os.path.realpath("."))
Using shutil
[ ]:
from shutil import copyfile, copy
copyfile(src, dst) # To copy a file from source to destination (using shutil)
copy(src, dst) # To copy a file or directory from source to destination (using shutil)
To create a directory if it doesn’t exist
[ ]:
import os
if not os.path.exists(directory):
os.makedirs(directory)
To write a JSON to a file
[ ]:
import json
with open('data.json', 'w') as f:
json.dump(data, f)