
Reading and Writing Files in Python (Guide)
Reading and Writing Files in Python (Guide) 관련

Watch Now
This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding:

One of the most common tasks that you can do with Python is reading and writing files. Whether it’s writing to a simple text file, reading a complicated server log, or even analyzing raw byte data, all of these situations require reading or writing a file.
In this tutorial, you’ll learn
- What makes up a file and why that’s important in Python
- The basics of reading and writing files in Python
- Some basic scenarios of reading and writing files
This tutorial is mainly for beginner to intermediate Pythonistas, but there are some tips in here that more advanced programmers may appreciate as well.
Quiz - Reading and Writing Files in Python

A quiz used for testing the user's knowledge of the topics covered in the Reading and Writing Files in Python article.




Don’t Re-Invent the Snake
There are common situations that you may encounter while working with files. Most of these cases can be handled using other modules. Two common file types you may need to work with are .csv
and .json
. Real Python has already put together some great articles on how to handle these:
Additionally, there are built-in libraries out there that you can use to help you:
wave
: read and write WAV files (audio)aifc
: read and write AIFF and AIFC files (audio)sunau
: read and write Sun AU filestarfile
: read and write tar archive fileszipfile
: work with ZIP archivesconfigparser
: easily create and parse configuration filesxml.etree.ElementTree
: create or read XML based filesmsilib
: read and write Microsoft Installer filesplistlib
: generate and parse Mac OS X.plist
files
There are plenty more out there. Additionally there are even more third party tools available on PyPI. Some popular ones are the following:
You’re a File Wizard Harry!
You did it! You now know how to work with files with Python, including some advanced techniques. Working with files in Python should now be easier than ever and is a rewarding feeling when you start doing it.
In this tutorial you’ve learned:
- What a file is
- How to open and close files properly
- How to read and write files
- Some advanced techniques when working with files
- Some libraries to work with common file types
If you have any questions, hit us up in the comments.
Quiz - Reading and Writing Files in Python

A quiz used for testing the user's knowledge of the topics covered in the Reading and Writing Files in Python article.
Watch Now
This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding:

