programming-fundamentals
  • Introduction
  • Lesson 1
    • Writing Your First Program
    • Data Types
    • Built In Functions
    • If Statements
    • Using Git and Github
    • Primer
    • Questions
    • Tip Calculator
    • GPA Calculator (optional)
  • Lesson 2
    • Modules
    • Lists
    • Data Structures
    • More On Data Structures
    • Questions
    • Madame Zamad
    • Mad Libs
  • Lesson 3
    • While Loops
    • For Loops
    • Loops and Lists
    • Special Commands
    • Questions
    • TODO List
    • Fibonacci (optional)
  • Lesson 4
    • Functions
    • More Functions
    • Error Handling
    • File I/O
    • Questions
    • Sudoku
Powered by GitBook
On this page
  • Files
  • Reading and Writing Files
  • The With Block

Was this helpful?

  1. Lesson 4

File I/O

PreviousError HandlingNextQuestions

Last updated 5 years ago

Was this helpful?

Files

Programs become more useful and interesting when they can interact with data that exists outside of the program. Almost all of the websites that you use store your data for their service in some kind of database or file system. That is how they can give you a persistent service. If we are going to be able to right persistent programs then we need to learn more about storing data. Databases are more of an advanced concept but for right now, the file system will do just fine.

Reading and Writing Files

Python makes interacting with files very simple. The built-in open() function provides us with a way to get a file object we can use.

file_obj = open('filename', 'r')

The modes you give it allow you to do different things with the file object. Below is a table of what is possible:

Mode

Capability

r

read

w

write

a

append to file

r+, w+, a+

read & write

b

binary

Please read the documentation for more information on the modes. To avoid messing things up you typically don't want to open a file with more permissions than you need. It's up to you though what you decide.

One thing you should always remember when dealing with files is that you should always close them when you are finished. If you fail to close a file, then you are taking up resources on the computer and other programs might fail because you are a hog.

The With Block

Since it can sometimes be a huge pain to remember to close resources Python has created a special block that will close resources when the block ends. The with block lets you open a file and use it to do whatever you want and then will close the file for you when you're finished.

with open('filename', 'r') as f:
  lines = f.readlines()

Remember the scoping rules for lines since it is within the with block. If an error were to occur while opening the file, then lines would not be declared. You can get around that by declaring lines outside of the block.

lines = None
with open('filename', 'r') as f:
  lines = f.readlines()

You could then catch any file I/O errors using a try/except block.

lines = None
try:
  with open('filename', 'r') as f:
    lines = f.readlines()
except IOError as e:
  print(str(e))

for line in lines:
  recite(line)

The function takes a filename (string) and a mode (string) and returns a file object.

Now that you have a file object, you can read from and write to the file you opened (assuming you used the appropriate mode). The has many functions that can let you do a lot of complex operations but the simple ones you should know about are: , , , , , and . The read functions ending in ...line(s) read the file and separate each line (using the '\n'). writelines() takes a list and writes each element in the list as a separate line. These are really handy helper functions that you can use to avoid writing a for loop to read and write files.

open()
File Object
read()
readline()
readlines()
write()
writelines()
close()
newline character