Python sys & os draft

Last modified 2 years ago / Edit on Github
The last modifications of this post were around 2 years ago, some information may be outdated!
This is a draft, the content is not complete and of poor quality!


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 = ''
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/
py scripts/ # returns: /home/thi

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

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

# 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
# The last modification
Support Thi Support Thi