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()
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'))
As soon as the with
block is exited, the file will be closed automatically.
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
Reading single lines with readline()
A single line can be read with readline()
.
#!/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'))
open is io.open
import io
print(io.open is open)
#
# True
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)
Returned type
open()
returns a object whose type is _io.TextIOWrapper
:
with open('type.py') as f:
print(type(f))
#
# <class '_io.TextIOWrapper'>
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)
See also
The standard library
os.path
has some functions related to files and filename manipulation.