OS and filesystem interaction with Python

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

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
# 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 environmentCSX_HOME=/home/user/citeseerx:

import os

Change the current working directory (CWD) temporarily and then return to the original working directory:

import os
# Switch to new working directory
# do something, e.g.
print(os.getcwd()) # yields /tmp
# And switch back to the original wd

Create a directory  (cf. mkdir -p):

os.makedirs("/tmp/newdir", <tt>0744</tt>) # with unix-like permissions (r:4, w:2, x:1)


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

Start a subprocess (e.g. a Bash script):

import subprocess
subprocess.call("/bin/ls") # will list the files in the current directory


Leave a Reply