Python Files I/O

  • In Python, you can read from and write to files to persist data beyond the lifetime of a program.
  • The open function is used to open a file, and the returned file object provides methods to interact with the file.

Example of how you could use file I/O to store information about a car:

When run, the code outputs:

In this example, the open function is used to open the file "car_info.txt" in write mode ("w"), and the file.write method is used to write the information about the car to the file. The with statement is used to ensure that the file is properly closed even if an exception occurs during execution of the block.

Later, the file is opened in read mode ("r"), and the file.read method is used to read the contents of the file into the car_info variable.

It’s also possible to read a file line by line using a for loop, like this:

When run, the code outputs:

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top