Python 3 - IO

Updated: 2018-06-27

Open

open as binary

open('filepath', 'rb')

use default codec(utf-8)

open('filepath')

Read

with open('filepath') as f:
    lines = f.read()

This will read all the lines at once, and may cause memory issue for large files.

To read and process the file line by line:

for line in open(path):
    do_something(line)

List Files

Returning a list of file names:

>>> import os
>>> os.listdir(path)
['foo.txt', 'bar.txt']

Paths

Remove if file already exists:

if os.path.exists(path):
    os.remove(path)

Remove dirs recursively if dir is empty:

os.rmdir(path)
os.removedirs(path)

Remove dirs recursively even if they are not empty:

shutil.rmtree(path)

Create folder if not exists:

if not os.path.exists(path):
    os.makedirs(path)

Expand Vars

This will find JAVA_HOME from your settings and expand it to the path.

open(os.path.expandvars('$JAVA_HOME/foo.bar'))

Read More