File Input and Output (I/O) is a fundamental aspect of any programming language and Python is no exception. It allows you to read and write data to and from files on your computer. In this article, we will explore the basics of working with file I/O in Python, including how to open, read, write and close files.
Opening Files
The first step in working with a file in Python is to open it. This is done using the built-in open() function. The open() function takes the file name and the mode as arguments. The mode determines how the file will be opened. The most common modes are ‘r’ for reading, ‘w’ for writing, and ‘a’ for appending. For example:
f = open('file.txt', 'r')
This will open the file named ‘file.txt’ in read mode.
Reading Files
Once the file is open, you can read its contents using the read() function. This function takes in the number of bytes to read as an argument, and it returns a string containing the contents of the file. For example:
f = open('file.txt', 'r')
contents = f.read()
print(contents)
f.close()
You can also use the readlines() function, which returns a list of strings, where each string is a line from the file.
f = open('file.txt', 'r')
lines = f.readlines()
for line in lines:
print(line)
f.close()
Writing Files
You can also write data to a file by opening it in write mode (‘w’) or append mode (‘a’). The write() function is used to write data to a file. For example:
f = open('file.txt', 'w')
f.write('Hello, world!')
f.close()
This will write ‘Hello, world!’ to the file ‘file.txt’ and overwrite any existing data in the file.
f = open('file.txt', 'a')
f.write('\nHello again!')
f.close()
This will append ‘Hello again!’ to the file ‘file.txt’
Closing Files
Once you are done working with a file, it is important to close it using the close() function. This will free up system resources and prevent potential errors. You can also use the with open() as
statement which automatically closes the file for you when you are done working with it. This is the recommended way of opening files in python.
with open('file.txt', 'r') as f:
contents = f.read()
print(contents)
In conclusion, file I/O is an essential aspect of programming, and Python provides a simple and easy-to-use interface for working with files. By learning how to open, read, write and close files, you can use Python to effectively read and write data to files in your programs.