Python File IO
File IO
The
open
function returns a file object.Basic syntax
open(filename, mode)
The mode parameter is a string that specifies permissions:
’r’
– read’w’
– write (existing file with same name is erased)’a’
– append’r+’
– read and write
Basic Methods on File Objects
read
– read the contents of a filereadline
– read a single line from the filewrite
– write to a fileclose
– close the fileFile objects can be treated as iterators
File Example
# copy the contents of one file to another
inFile = open('myfile_in')
outFile = open('myfile_out', 'w')
for line in file:
outFile.write(line)
inFile.close()
outFile.close()
The with
Keyword
The
with
keyword can be used for a category of objects called context managers.A context manager has implementations of the
__enter__
and__exit__
methods.The
with
statement guarantees that the__exit__
method is called at the end of the block.The
__exit__
method of a file object closes the file.Example:
with open('myfile.txt', 'w') as f: f.write('Hello world!') # the file is guaranteed to be closed here
File Formats
Python has many modules to handle many file formats commonly used in data science tasks:
Comma separated values (CSV)
Hypertext Markup Language (HTML)
Extensible Markup Language (XML)
JavaScript Object Notation (JSON)
Sqlite database files