read()
, readline()
, readlines()
)with
statement for clean file handlingWhat is File Handling?
File handling allows your Python program to interact with files on your computer: reading data from files or writing data to them.
Python provides built-in functions to work with files using:
open(filename, mode)
Mode | Description |
---|---|
'r' | Read (default) – Error if file doesn't exist |
'w' | Write – Creates file or overwrites if it exists |
'a' | Append – Creates file or appends if it exists |
'x' | Create – Creates new file; fails if file exists |
'b' | Binary mode (e.g., 'rb' , 'wb' ) |
't' | Text mode (default) |
file = open("data.txt", "r") # Opens in read mode
Always close a file when you;re done:
file.close()
But instead of manually opening and closing, it's better to use with
statement (explained below).
read()
: Reads the entire file
with open("data.txt", "r") as f:
content = f.read()
print(content)
readline()
: Reads one line at a time
with open("data.txt", "r") as f:
line1 = f.readline()
line2 = f.readline()
print(line1, line2)
readlines()
: Reads all lines into a list
with open("data.txt", "r") as f:
lines = f.readlines()
for line in lines:
print(line.strip())
'w'
mode overwrites the file:
with open("data.txt", "w") as f:
f.write("Hello, Akash!\n")
f.write("Welcome to Python file handling tutorial.")
'a'
mode adds content to the end:
with open("data.txt", "a") as f:
f.write("\nThis is an additional line.")
with
Statement (Context Manager)The with
statement automatically close the file even if an error occurs.
with open("data.txt", "r") as f:
data = f.read()
print(data)
# File is now close automatically
with
?file.close()
To avoid errors across platforms, use os.path
:
import os
path = os.path.join("folder", "data.txt")
with open(path, "r") as f:
print(f.read())
or use absolute paths carefully:
with open("/home/akash/documents/data.txt") as f:
...
with
)'w'
instead of 'a'
when you want to appendos.path.exists()
if needed)🔸 Create text file named log.txt
. Write a Python script that:
log.txt
.💡 Hint: Use datetime.now()
from the datetime
module.
Operation | Method/Example |
---|---|
Read entire | read() |
Read one line | readline() |
Read all lines | readlines() |
Write file | write() in 'w' mode |
Append file | write() in 'a' mode |
Safe handling | with open(...) as f: |
Paths | os.path.join() for safe paths |
Leave a Reply