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:

Get the path to the current file (with the help of the magic variable __file__)

Determine directory of a file (similar to dirname Bash command):

Copy a directory recursively (contents of “/tmp/test1/”  to “/tmp/test2″):

Remove a directory recursively:

Export the following mapping to the environmentCSX_HOME=/home/user/citeseerx:

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

Create a directory  (cf. mkdir -p):

Files

Write a raw string to the file /tmp/testfile.txt:

Read file to string:

Copy file to directory:

Renaming a file:

Process Management

Exit with a certain exit code (here: 1):

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

Links

Leave a Reply