Search notes:

Python: open()

open is used to open a file for reading or writing. The function returns a file object.

Writing a file

The following example is a Python script that prints its own content. (__file__ evaluates to the filename of the script):
f_in = open(__file__, 'r') # Note 'r' is default (could be omitted here)

print("".join( f_in.readlines() ))

f_out = open('open.out', 'w')
f_out.write("Hello world\n")
f_out.write("The number is: 42\n")
f_out.close()
Github repository about-python, path: /built-in/functions/open/demo.py

Using open together with a with statement

Because the file that is opened should eventually be closed, it is advisable to use open() together with a with statement.
with open(__file__, 'r') as thisSourceFile:

     for line in thisSourceFile:
         print('line>', line.rstrip('\n'))
Github repository about-python, path: /built-in/functions/open/with.py
As soon as the with block is exited, the file will be closed automatically.
See also context managers.

Using next()

The object that is returned by open(…, 'r') is an iterator. Thus, it is possible to read a line from the file being read with next().
next() throws a StopIteration exception when there are no more lines to be read:
import os

def readALine(fil):
    try:
       lin = next(fil)
       print('Line that was read is:', lin.rstrip("\n"))
       return True
    except StopIteration:
       return False


fil = open(os.path.dirname(__file__) + '/lines.txt', 'r')

while readALine(fil): pass

Github repository about-python, path: /built-in/functions/open/next.py

Reading single lines with readline()

A single line can be read with readline().
The text returned by readline() still has the end of line character which might be removed with str.rstrip('\n\r').
#!/usr/bin/python
import sys

f = open(__file__)
l1 = f.readline()
l2 = f.readline()
l3 = f.readline()
l4 = f.readline()

print(l4.rstrip('\n'))
print(l3.rstrip('\n'))
print(l2.rstrip('\n'))
print(l1.rstrip('\n'))
Github repository about-python, path: /built-in/functions/open/readline.py

open is io.open

open() is defined in the function open() of the io module. This can be verified with the is operator:
import io

print(io.open is open)
#
#  True
Github repository about-python, path: /built-in/functions/open/open-is-io.open.py

Opening a UTF-8 file

In Python 3, open has an encoding parameter which can be used, for example, if an UTF-8 file is read.
with open('file.utf8', 'r', encoding='utf-8') as fil:
     for lin in fil:
         lin=lin.rstrip('\n\r')
         print(lin)
Github repository about-python, path: /built-in/functions/open/open-utf8.py

Returned type

open() returns a object whose type is _io.TextIOWrapper:
with open('type.py') as f:
     print(type(f))
#
# <class '_io.TextIOWrapper'>
Github repository about-python, path: /built-in/functions/open/type.py

Slurping a file into a variable

The content of a file can be slurped into a variable like so:
import sys

path_to_script = sys.argv[0]
with open(path_to_script) as f:
     this_script_as_text  = f.read()

print(this_script_as_text)
Github repository about-python, path: /built-in/functions/open/slurp.py

See also

Iterate over each line in a file.
Using iter() and open() to iterate over each line in a file.
open() can also be used to open a reference to sys.stdin, sys.stdout or sys.stderr.
The standard library os has functions to create directories and to remove files and directories
The standard library os.path has some functions related to files and filename manipulation.
Especially interesting are those that check for the existence of files and directories.
Python: Built in functions
Python: (some) _io types

Index