Python sys & os draft

Last modified 2 years ago / Edit on Github
Warning
This post was updated more than 1 year ago, some information may be outdated!
Warning
This is a draft, the content is not complete and of poor quality!

Libraries

import os, sys
import shutil

Copy and move

shutil.copy('/Users/a/file.txt', '/Users/b/file.txt')
# Move a file from /Users/a/file.txt to /Users/b/
# (cannot replace)
shutil.move('/Users/a/file.txt', '/Users/b/')

# Move and replace
shutil.move('/Users/a/file.txt', '/Users/b/file.txt')

Append path to the environnement

sys.path.append('../') # the path of current file's father

Get files' info

# Find location first and then get the path
file = 'abc.xyz'
for root, _, files in os.walk(r'D:\python'):
for name in files:
if name == file:
print (os.path.abspath(os.path.join(root, name)))
# Get current working directory

# We're in /home/thi/
print(os.getcwd()) # in /home/thi/scripts/helper.py
py scripts/helper.py # returns: /home/thi

# We're in /home/thi/
print(os.path.dirname(__file__)) # in /home/thi/scripts/helper.py
py scripts/helper.py # returns: /home/thi/scripts

os.path.dirname(__file__) # returns: /home/thi/scripts/helper.py

# NOTE: We have to call a file to make "__file__" work!

# We can use in a jupyter notebook
from helper import test
# test = os.path.dirname(__file__)
# List of all files in a path
file_path = '.' # current dir
os.listdir(file_path)
# The last modification
os.path.getmtime(<full-path-to-file-name>)