Key Concepts

Review core concepts you need to learn to master this subject

Python File Object

A Python file object is created when a file is opened with the open() function. You can associate this file object with a variable when you open a file using the with and as keywords. For example:

with open('somefile.txt') as file_object:

You can then print the content of the file object, file_object with print().


You might see something like this on the output terminal:

<_io.TextIOWrapper name='somefile.txt' mode='r' encoding='UTF-8'>

Python Readline Method

To read only one line instead of multiple lines in a Python file, use the method .readline() on a file object that is returned from the open() function. Every subsequent .readline() will extract the next line in the file if it exists.

with open('story.txt') as story_object: print(story_object.readline())

will print only the first line in story.txt.

Python Append To File

Writing to an opened file with the 'w' flag overwrites all previous content in the file. To avoid this, we can append to a file instead. Use the 'a' flag as the second argument to open(). If a file doesn’t exist, it will be created for append mode.

with open('shopping.txt', 'a') as shop: shop.write('Tomatoes, cucumbers, celery\n')

Python Write To File

By default, a file when opened with open() is only for reading. A second argument 'r' is passed to it by default. To write to a file, first open the file with write permission via the 'w' argument. Then use the .write() method to write to the file. If the file already exists, all prior content will be overwritten.

with open('diary.txt','w') as diary: diary.write('Special events for today')

Python Readlines Method

Instead of reading the entire content of a file, you can read a single line at a time. Instead of .read() which returns a string, call .readlines() to return a list of strings, each representing an individual line in the file. Calling this code:

with open('lines.txt') as file_object: file_data = file_object.readlines() print(file_data)

returns a list of strings in file_data:

['1. Learn Python.\n', '2. Work hard.\n', '3. Graduate.']

Iterating over the list, file_data, and printing it:

for line in file_data: print(line)


1. Learn Python. 2. Work hard. 3. Graduate.

Class csv.DictWriter

In Python, the csv module implements classes to read and write tabular data in CSV format. It has a class DictWriter which operates like a regular writer but maps a dictionary onto output rows. The keys of the dictionary are column names while values are actual data.

The csv.DictWriter constructor takes two arguments. The first is the open file handler that the CSV is being written to. The second named parameter, fieldnames, is a list of field names that the CSV is going to handle.

Python Read Method

After a file is opened with open() returning a file object, call the .read() method of the file object to return the entire file content as a Python string. Executing the following Python code:

with open('mystery.txt') as text_file: text_data = print(text_data)

will produce a string containing the entire content of the read file:

Mystery solved. Congratulations!
Learn Python: Files
Lesson 1 of 1
  1. 1
    Computers use file systems to store and retrieve data. Each file is an individual container of related information. If you’ve ever saved a document, downloaded a song, or even sent an email you’ve …
  2. 2
    When we read a file, we might want to grab the whole document in a single string, like .read() would return. But what if we wanted to store each line in a variable? We can use the .readlines() func…
  3. 3
    Sometimes you don’t want to iterate through a whole file. For that, there’s a different file method, .readline(), which will only read a single line at a time. If the entire document is read line b…
  4. 4
    Reading a file is all well and good, but what if we want to create a file of our own? With Python we can do just that. It turns out that our open() function that we’re using to open a file to read …
  5. 5
    So maybe completely deleting and overwriting existing files is something that bothers you. Isn’t there a way to just add a line to a file without completely deleting it? Of course there is! Instead…
  6. 6
    We’ve been opening these files with this with block so far, but it seems a little weird that we can only use our file variable in the indented block. Why is that? The with keyword invokes something…
  7. 7
    Text files aren’t the only thing that Python can read, but they’re the only thing that we don’t need any additional parsing library to understand. CSV files are an example of a text file that impos…
  8. 8
    Recall our CSV file from our last exercise: users.csv Name,Username,Email Roger Smith,rsmith,[email protected] Michelle Beck,mlbeck,[email protected] Ashley Barker,a_bark_x,[email protected]
  9. 9
    I need to level with you, I’ve been lying to you for the past two exercises. Well, kind of. We’ve been acting like CSV files are Comma-Separated Values files. It’s true that CSV stands for that, bu…
  10. 10
    Naturally if we have the ability to read different CSV files we might want to be able to programmatically create CSV files that save output and data that someone could load into their spreadsheet s…
  11. 11
    CSV isn’t the only file format that Python has a built-in library for. We can also use Python’s file tools to read and write JSON. JSON, an abbreviation of JavaScript Object Notation, is a file for…
  12. 12
    Naturally we can use the json library to translate Python objects to JSON as well. This is especially useful in instances where you’re using a Python library to serve web pages, you would also be a…
  13. 13
    Now you know all about files! You were able to: - Open up file objects using open() and with. - Read a file’s full contents using Python’s .read() method. - Read a file line-by-line using .read…

What you'll create

Portfolio projects that showcase your new skills

Pro Logo

How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory

Pro Logo