Directories and Environment
Note: The import statements are repeated for every code sample just to show you what modules you need. In real operation, of course, the modules need only be imported once.
Check whether a file/directory exists:
import os print("File /tmp/test2 exists? " + str(os.path.exists("/tmp/test2")==False))
Get the path to the current file (with the help of the magic variable __file__)
import os os.path.abspath(__file__)
Determine directory of a file (similar to dirname Bash command):
import os directory = os.path.dirname("/tmp/test/testfile.txt") print(directory) # yields /tmp/test
Copy a directory recursively (contents of “/tmp/test1/” to “/tmp/test2″):
import shutil shutil.copytree("/tmp/test1", "/tmp/test2")
Remove a directory recursively:
import shutil shutil.rmtree("/tmp/test2") # The above call will produce an error if the directory exists, the following command ignores errors: shutil.rmtree("/tmp/test2", ignore_errors = True)
Export the following mapping to the environment: CSX_HOME=/home/user/citeseerx:
import os os.environ["CSX_HOME"]="/home/user/citeseerx" print(os.environ["CSX_HOME"])
Change the current working directory (CWD) temporarily and then return to the original working directory:
import os old_directory=os.getcwd() # Switch to new working directory os.chdir("/tmp") # do something, e.g. print(os.getcwd()) # yields /tmp # And switch back to the original wd os.chdir(old_directory)
Create a directory (cf. mkdir -p):
os.makedirs("/tmp/newdir") os.makedirs("/tmp/newdir", <tt>0744</tt>) # with unix-like permissions (r:4, w:2, x:1)
Files
Write a raw string to the file /tmp/testfile.txt:
open("/tmp/testfile.txt", 'w').write("Hello World, this is my file contentn") # verify content e.g. with Bash command: cat /tmp/testfile.txt
Read file to string:
content = open("/tmp/testfile.txt", 'r').read() print(content) # yields "Hello World, this is my file content" for the previous example
Copy file to directory:
import shutil shutil.copy("/tmp/testfile1.txt", "/tmp/testdir")
Renaming a file:
import os os.rename("a.txt", "b.txt")
Process Management
Exit with a certain exit code (here: 1):
import sys sys.exit(1)
Start a subprocess (e.g. a Bash script):
import subprocess subprocess.call("/bin/ls") # will list the files in the current directory
Links
- os module Reference
- os.path module Reference
- shutil module Reference