Working With Files in Python (34/100 Days of Python)
Files are a fundamental part of computer programming, as they allow you to store data and information on your computer. In Python, you can interact with files in many ways, including opening, closing, reading, and writing. In this tutorial, we will cover the basics of working with files in Python.
Opening a File in Python
To open a file in Python, you use the built-in open
function. The open
function takes two arguments: the name of the file you want to open and the mode in which you want to open it. There are several modes you can use to open a file, including 'r'
for reading, 'w'
for writing, and 'a'
for appending. We can open a file named example.txt
for reading:
f = open('example.txt', 'r')
When you are done working with the file, you should close it to free up resources. You can close a file in Python by using the close
method:
f.close()
Reading a File in Python
Once you have opened a file for reading, you can read its contents in several ways. You can read the entire file as a single string by using the read
method:
f = open('example.txt', 'r')
contents = f.read()
f.close()
You can also read the file line by line using a for
loop:
f = open('example.txt', 'r')
for line in f:
print(line)
f.close()
Writing to a File in Python
To write to a file in Python, you need to open the file in write mode. For example, to open a file named example.txt
for writing, you would use the following code:
f = open('example.txt', 'w')
To write to the file, you use the write
method. For example, to write a string to the file, you would use the following code:
f.write('Hello, World!')
f.close()
If you open a file in write mode and write to it, any existing contents of the file will be overwritten. To append to a file, you can open it in append mode:
f = open('example.txt', 'a')
f.write('\nHello, again!')
f.close()
If we run these 3 two code snippets one after another, the file will contain 2 lines as the second time the file was open in the append mode — so the write()
function added the new text to the opened file:
Hello, World!
Hello, again!
What’s next?
- If you found this story valuable, please consider clapping multiple times (this really helps a lot!)
- Hands-on Practice: Free Python Course — work with files
- Full series: 100 Days of Python
- Previous topic: Higher Order Functions
- Next topic: With Statement