File handling is a critical aspect of programming that involves reading and writing data to and from files on a computer. In Python, there are several built-in functions and modules that allow for easy file handling. Here are some basic concepts and functions related to file handling in Python:
Opening and Closing Files
To access a file for reading or writing, it must first be opened. The open() function is used to open a file in Python, and it takes two arguments: the file name and the mode (read, write, append, etc.). For example, to open a file called example.txt for reading, we would use the following code:
python
Copy code
file = open('example.txt', 'r')
After we have finished working with the file, we should close it using the close() method to ensure that all changes are saved and any resources allocated for the file are released. Here's an example of closing a file:
python
Copy code
file.close()
Reading Files
Once a file has been opened, we can read its contents using various methods. The most basic method is the read() method, which reads the entire contents of a file as a single string. Here's an example:
python
Copy code
file = open('example.txt', 'r')
contents = file.read()
print(contents)
file.close()
We can also read a file line by line using the readline() method, which reads one line at a time. Here's an example:
python
Copy code
file = open('example.txt', 'r')
line1 = file.readline()
line2 = file.readline()
print(line1)
print(line2)
file.close()
Alternatively, we can read all the lines of a file at once and store them in a list using the readlines() method. Here's an example:
python
Copy code
file = open('example.txt', 'r')
lines = file.readlines()
for line in lines:
print(line)
file.close()
Writing Files
To write data to a file, we can use the write() method. Here's an example of writing a string to a file:
python
Copy code
file = open('example.txt', 'w')
file.write("This is a test.\n")
file.close()
Note that the mode argument for open() has been set to 'w', indicating that we are opening the file for writing. If the file already exists, its contents will be overwritten. To append data to an existing file, we can use the 'a' mode instead.
Exception Handling
When working with files, it's important to handle exceptions properly. For example, if the file we're trying to read doesn't exist, we should catch the FileNotFoundError exception and handle it accordingly. Here's an example:
python
Copy code
try:
file = open('example.txt', 'r')
contents = file.read()
print(contents)
file.close()
except FileNotFoundError:
print("File not found.")
In this example, if the file 'example.txt' doesn't exist, the program will print "File not found." instead of crashing with an error message.