Python provides built-in methods to read from and write to files using file objects. The most commonly used methods are:
read()
โ Reads file content.write()
โ Writes data to a file.
๐น Writing to a File Using write()
- You must open the file in write (
'w'
) or append ('a'
) mode. - The method returns the number of characters written.
- Existing content is overwritten in
'w'
mode.
# Open a file in write mode
file = open("example.txt", "w")
# Write data to the file
file.write("Hello, World!\n")
file.write("Python file handling is simple.\n")
# Close the file
file.close()
โ
Output in example.txt
:
Hello, World!
Python file handling is simple.
๐น Appending to a File ('a'
Mode)
file = open("example.txt", "a")
file.write("Appending a new line.\n")
file.close()
โ Adds new content without overwriting existing data.
๐น Reading from a File Using read()
To read a file, open it in read mode ('r'
).
# Open the file in read mode
file = open("example.txt", "r")
# Read the entire file content
content = file.read()
print(content)
# Close the file
file.close()
โ Output (prints file content):
Hello, World!
Python file handling is simple.
Appending a new line.
๐น Reading Only a Certain Number of Characters
file = open("example.txt", "r")
print(file.read(10)) # Reads only the first 10 characters
file.close()
โ Output:
Hello, Wor
๐น Reading Line by Line
๐น Using readline()
โ Reads a Single Line
file = open("example.txt", "r")
print(file.readline()) # Reads the first line
file.close()
โ Output:
Hello, World!
๐น Using readlines()
โ Reads All Lines into a List
file = open("example.txt", "r")
lines = file.readlines() # Returns a list of lines
file.close()
print(lines)
โ Output:
['Hello, World!\n', 'Python file handling is simple.\n', 'Appending a new line.\n']
๐น Best Practice: Using with open()
with open()
automatically closes the file after reading or writing.
with open("example.txt", "r") as file:
content = file.read()
print(content) # File is automatically closed after this block
๐น Writing and Reading ('w+'
and 'r+'
Modes)
'w+'
โ Overwrites the file, then allows reading.'r+'
โ Reads first, then allows writing.
๐น Using 'w+'
Mode
with open("example.txt", "w+") as file:
file.write("New content.\n") # Overwrites existing content
file.seek(0) # Move cursor back to the beginning
print(file.read()) # Read the file
โ Output:
New content.
๐น Using 'r+'
Mode
with open("example.txt", "r+") as file:
print(file.read()) # Read the existing content
file.write("\nAdding more data!") # Write new data
โ Appends data at the end while keeping old content.
๐น Summary Table
Mode | Description |
---|---|
'r' |
Read (default). File must exist. |
'w' |
Write (creates/overwrites file). |
'a' |
Append (adds data at the end). |
'r+' |
Read + Write (does not delete content). |
'w+' |
Write + Read (overwrites file). |
'a+' |
Append + Read (adds data, keeps old content). |
Would you like examples for working with CSV files or binary files? ๐
Leave a Reply