File Handling in Python
1. Basics of File Handling
Python uses the open() function to work with files. The syntax is:
file = open("filename", mode)
Modes for Opening Files:
Mode Description
r Read mode (default).
w Write mode. Overwrites if file exists.
a Append mode. Adds data to the end.
x Create mode. Fails if file exists.
b Binary mode.
t Text mode (default).
2. Reading Files
Reading the Entire File:
with open("example.txt", "r") as file:
content = file.read()
print(content)
Reading Line by Line:
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
Reading Specific Number of Characters:
with open("example.txt", "r") as file:
, content = file.read(10) # Reads the first 10 characters
print(content)
3. Writing to Files
Writing a New File:
with open("output.txt", "w") as file:
file.write("This is a new file.\n")
file.write("File handling is easy in Python.")
Appending to a File:
with open("output.txt", "a") as file:
file.write("\nAdding another line.")
4. File Methods
Method Description
read() Reads the entire file content.
readline() Reads one line at a time.
readlines() Reads all lines and returns them as a list.
write() Writes a string to the file.
writelines() Writes a list of strings to the file.
Example:
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("output.txt", "w") as file:
file.writelines(lines)
5. File Positioning
Use the tell() method to get the current file position.
1. Basics of File Handling
Python uses the open() function to work with files. The syntax is:
file = open("filename", mode)
Modes for Opening Files:
Mode Description
r Read mode (default).
w Write mode. Overwrites if file exists.
a Append mode. Adds data to the end.
x Create mode. Fails if file exists.
b Binary mode.
t Text mode (default).
2. Reading Files
Reading the Entire File:
with open("example.txt", "r") as file:
content = file.read()
print(content)
Reading Line by Line:
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
Reading Specific Number of Characters:
with open("example.txt", "r") as file:
, content = file.read(10) # Reads the first 10 characters
print(content)
3. Writing to Files
Writing a New File:
with open("output.txt", "w") as file:
file.write("This is a new file.\n")
file.write("File handling is easy in Python.")
Appending to a File:
with open("output.txt", "a") as file:
file.write("\nAdding another line.")
4. File Methods
Method Description
read() Reads the entire file content.
readline() Reads one line at a time.
readlines() Reads all lines and returns them as a list.
write() Writes a string to the file.
writelines() Writes a list of strings to the file.
Example:
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("output.txt", "w") as file:
file.writelines(lines)
5. File Positioning
Use the tell() method to get the current file position.