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.

Code

with open('filename.txt', 'r') as file:
    content = file.read()
print(content)

Output

Contents of filename.txt

b. Writing to a file: You can use the 'write' method to write data to a file.

Code

with open('filename.txt', 'w') as file:
    file.write('Hello, World!')

Output

"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.

Code

with open('filename.txt', 'a') as file:
    file.write('\nAppended Text.')

Output

"Appended Text." is added to filename.txt on a new line

Enquiries

[email protected]

Copyright © 2023 - slash-root.com