Selected topic
File Handling
Prefer practical output? Use related tools below while reading.
=====================================
Python provides a built-in module called io (Input/Output) to handle files. The following are the basic file handling operations:
### Opening and Closing Files
open() function, which returns a file object.python
# Open a file in read mode
file = open("example.txt", "r")# Open a file in write mode
file = open("example.txt", "w")
close() method or the with statement.python
# Close the file using the close() method
file.close()# Close the file using the with statement (recommended)
with open("example.txt", "r") as file:
print(file.read())
### Reading from Files
readline().python
file = open("example.txt", "r")
print(file.readline())
python
file = open("example.txt", "r")
for line in file:
print(line)### Writing to Files
write() method.python
file = open("example.txt", "w")
file.write("Hello, World!")
"a").python
file = open("example.txt", "a")
file.write("\nThis is a new line.")### Example Use Case
Suppose you have a file called names.txt containing the names of your friends, one per line. You want to read the names from this file and write them to another file called output.txt.
python
with open("names.txt", "r") as input_file:
with open("output.txt", "w") as output_file:
for name in input_file:
output_file.write(name)This code opens names.txt for reading and output.txt for writing, then reads each line from names.txt and writes it to output.txt. When you're done with both files, they are automatically closed.
Remember to always close your files when you're finished using them. You can use the with statement or the close() method to do this.