Python Fundamentals: Reading and Writing Files
Handling files is an essential part of programming. Python provides built-in functions to read and write files.
a. Reading from a file: The 'open' function is used to open a file. To read from it, you can use the 'read' method.
with open('filename.txt', 'r') as file:
content = file.read()
b. Writing to a file: You can use the 'write' method to write data to a file.
with open('filename.txt', 'w') as file:
"Hello, World!" is written to filename.txt
c. Appending to a file: To add data to an existing file without overwriting its content, use the 'append' mode.
with open('filename.txt', 'a') as file:
"Appended Text." is added to filename.txt on a new line
Copyright © 2023 - slash-root.com