Selected topic

File Handling

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

  • Opening a File: You can open a file using the 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")


  • Closing a File: Always close the file when you are done with it to free up system resources. You can use the 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

  • Reading a Single Line: You can read a single line of text from a file by calling readline().
python
file = open("example.txt", "r")
print(file.readline())
  • Reading Multiple Lines: You can read multiple lines using a loop.
python
file = open("example.txt", "r")
for line in file:
    print(line)

### Writing to Files

  • Writing Text: You can write text to a file using the write() method.
python
file = open("example.txt", "w")
file.write("Hello, World!")
  • Appending Text: You can append text to an existing file by opening it in append mode ("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.