File Handling in Python

 File Handling in Python


File handling is used to read from and write to files in Python. Here's an example of how to read from a file:


python


file = open("example.txt", "r")

content = file.read()

print(content)

file.close()

In this example, we use the open() function to open a file called "example.txt" in read mode. We then use the read() method to read the contents of the file into the content variable. Finally, we close the file using the close() method.


We can also write to a file:


python


file = open("example.txt", "w")

file.write("Hello, world!")

file.close()

In this example, we use the open() function to open a file called "example.txt" in write mode. We then use the write() method to write the string "Hello, world!" to the file. Finally, we close the file using the close() method.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...