Python File I/O Basics: open(), read(), write() Made Simple
Python File I/O Basics: open(), read(), write() Made Simple ๐
File input and output (I/O) operations are essential skills for any developer.
In Python, you can easily open, read, and write files using the open(), read(), and write() functions.
✅ Opening and Reading a File
Use open() with mode 'r' (read) to read the contents of a file easily.
# Opening and reading a file
with open('sample.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
✅ Writing to a File
Set the mode to 'w' to overwrite or create a new file and write data into it.
# Opening and writing to a file
with open('output.txt', 'w', encoding='utf-8') as file:
file.write("Hello, Python file I/O!")
✅ Reading Line by Line
For large files, reading line by line using a for loop is memory-efficient and clean.
# Reading a file line by line
with open('sample.txt', 'r', encoding='utf-8') as file:
for line in file:
print(line.strip())
Using a with block ensures the file is properly closed after the operation, avoiding resource leaks.
File I/O is a fundamental building block for logging, configuration management, and handling external data.
Handling files is the first step to handling real-world data. Master the basics, and the rest will come naturally. Keep building, keep growing — you're on the right track! ๐
Icons by Flaticon
Comments
Post a Comment