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.

CharacterMeaning
'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 Repl.it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.