File Handling in Python (Basics)
Python reads and writes files with the built-in open() function:
file = open("filename", "mode")
| Mode | Meaning |
|---|---|
"r" | Read (default). Error if the file does not exist. |
"w" | Write. Creates the file and erases old content if it exists. |
"a" | Append. Creates the file and adds new content at the end. |
"x" | Create. Error if the file already exists. |
Always close a file after use, or better, use the with statement: it closes the file for you, even if an error happens.
1. Write to a file ("w" mode)
file = open(file_name, "w")
file.write("Hello Students\n") # \n means new line
file.write("Welcome to File Handling\n")
file.close() # don't forget to close
print("1. Data written to", file_name)
2. Read the whole file ("r" mode)
file = open(file_name, "r")
data = file.read()
print("\n2. Full file content:")
print(data)
file.close()
3. "with" statement (best way)
"with" closes the file automatically, even if an error happens.
with open(file_name, "r") as file:
print("3. Read using with:")
print(file.read())
4. Append to a file ("a" mode)
Old content stays, new content is added at the end.
with open(file_name, "a") as file:
file.write("Python is easy\n")
file.write("Practice daily\n")
print("4. Two more lines appended")
5. Read one line at a time
with open(file_name, "r") as file:
first_line = file.readline() # reads only the first line
second_line = file.readline() # reads the next line
print("\n5. readline():")
print("First line :", first_line.strip()) # strip() removes \n
print("Second line:", second_line.strip())
6. Read all lines into a list
with open(file_name, "r") as file:
lines = file.readlines()
print("\n6. readlines() gives a list:")
print(lines)
7. Loop over the file line by line
print("\n7. Loop over lines with line numbers:")
with open(file_name, "r") as file:
line_no = 1
for line in file:
print(line_no, "->", line.strip())
line_no += 1
8. Write a list of lines
fruits = ["Apple\n", "Banana\n", "Mango\n"]
with open("fruits.txt", "w") as file:
file.writelines(fruits)
print("\n8. fruits.txt created using writelines()")
9. Count lines, words and characters
with open(file_name, "r") as file:
content = file.read()
print("\n9. Counting in", file_name)
print("Lines :", len(content.splitlines()))
print("Words :", len(content.split()))
print("Characters:", len(content))
10. Check if a file exists
print("\n10. Check file exists:")
if os.path.exists("fruits.txt"):
print("fruits.txt exists")
else:
print("fruits.txt not found")
11. Handle "file not found" error
print("\n11. Reading a missing file:")
try:
with open("no_such_file.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("Error: file not found")
12. Rename and delete a file
os.rename("fruits.txt", "my_fruits.txt")
print("\n12. fruits.txt renamed to my_fruits.txt")
os.remove("my_fruits.txt")
print(" my_fruits.txt deleted")