Welcome to the “Reading & Writing Files” tutorial!
Overview
Python provides built-in functions to open, read, write, and close files.
Opening Files
# mode: 'r'=read, 'w'=write, 'a'=append, 'b'=binary
file = open('example.txt', 'r')
Reading Files
content = file.read() # entire file as a string
line = file.readline() # one line
lines = file.readlines() # list of lines
Writing Files
with open('output.txt', 'w') as file:
file.write('Hello, World!\n')
file.writelines(['Line 1\n', 'Line 2\n'])
Closing Files
file = open('data.txt', 'r')
# ... work with file ...
file.close()
Tip: It’s safest to use with
so files are closed automatically.
Key Takeaways
- Use
open()
with the correct mode. - Always close files or use
with open(...)
. - Reading methods:
.read()
,.readline()
,.readlines()
. - Writing methods:
.write()
,.writelines()
.
Happy coding!
Comments
Post a Comment