File I/O

Reading and writing files.

Working with paths

In [1]:
import os

current_file = os.path.realpath('file_io.ipynb')  
print('current file: {}'.format(current_file))
# Note: in .py files you can get the path of current file by __file__

current_dir = os.path.dirname(current_file)  
print('current directory: {}'.format(current_dir))
# Note: in .py files you can get the dir of current file by os.path.dirname(__file__)

data_dir = os.path.join(os.path.dirname(current_dir), 'data')
print('data directory: {}'.format(data_dir))
current file: /Users/jerry/github/jerry-git/learn-python3/notebooks/beginner/notebooks/file_io.ipynb
current directory: /Users/jerry/github/jerry-git/learn-python3/notebooks/beginner/notebooks
data directory: /Users/jerry/github/jerry-git/learn-python3/notebooks/beginner/data

Checking if path exists

In [2]:
print('exists: {}'.format(os.path.exists(data_dir)))
print('is file: {}'.format(os.path.isfile(data_dir)))
print('is directory: {}'.format(os.path.isdir(data_dir)))
exists: True
is file: False
is directory: True

Reading files

In [3]:
file_path = os.path.join(data_dir, 'simple_file.txt')

with open(file_path, 'r') as simple_file:
    for line in simple_file:
        print(line.strip())
First line
Second line
Third
And so the story goes!

The with statement is for obtaining a context manager that will be used as an execution context for the commands inside the with. Context managers guarantee that certain operations are done when exiting the context.

In this case, the context manager guarantees that simple_file.close() is implicitly called when exiting the context. This is a way to make developers life easier: you don't have to remember to explicitly close the file you openened nor be worried about an exception occuring while the file is open. Unclosed file maybe a source of a resource leak. Thus, prefer using with open() structure always with file I/O.

To have an example, the same as above without the with.

In [4]:
file_path = os.path.join(data_dir, 'simple_file.txt')

# THIS IS NOT THE PREFERRED WAY
simple_file = open(file_path, 'r')
for line in simple_file:
    print(line.strip())
simple_file.close()  # This has to be called explicitly 
First line
Second line
Third
And so the story goes!

Writing files

In [5]:
new_file_path = os.path.join(data_dir, 'new_file.txt')

with open(new_file_path, 'w') as my_file:
    my_file.write('This is my first file that I wrote with Python.')

Now go and check that there is a new_file.txt in the data directory. After that you can delete the file by:

In [6]:
if os.path.exists(new_file_path):  # make sure it's there
    os.remove(new_file_path)