Using Python: Part 2: File Input and Output

Learning Python

Using Python

Python is a general-purpose interpreted programming language. It emphasizes readability through the use of whitespace and supports multiple programming paradigms such as functional and object-oriented models.

File Input and Output

In Python, working with files starts with a single function, open().

File Input

The first parameter of open() is the file to open. After that is the mode of file access.

'r'open for reading (default)
'w'open for writing, truncating the file first
'x'open for exclusive creation, failing if the file already exists
'a'open for writing, appending to the end of the file if it exists
'b'binary mode
't'text mode (default)
'+'open a disk file for updating (reading and writing)

To work with files, there are three different functions:

  • read(): return one big string
  • readline: return one line at a time
  • readlines: returns a list of lines

File Output

For writing to files, there are two functions:

  • write(): Save sequence of characters to a file
  • writelines(): Save a list of strings.

Play with the example on!