File I/O in Python

 File I/O in Python


File I/O is used to read and write files on the computer. Here's an example of reading a text file:


python


with open("myfile.txt", "r") as f:

    contents = f.read()

    print(contents)

In this example, we open the file "myfile.txt" using the open function. We use the with statement to ensure that the file is closed properly after we are done reading it. We then read the contents of the file using the read method, and print the contents to the console.


Here's an example of writing to a text file:


python


with open("myfile.txt", "w") as f:

    f.write("Hello, world!")

In this example, we open the file "myfile.txt" for writing using the open function with the mode "w". We use the with statement to ensure that the file is closed properly after we are done writing to it. We then write the string "Hello, world!" to the file using the write 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...