- 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Writing to a file with open("car_info.txt", "w") as file: file.write("Make: Toyota\n") file.write("Model: Corolla\n") file.write("Year: 2020\n") # Reading from a file with open("car_info.txt", "r") as file: car_info = file.read() # Printing the contents of the file print(car_info) |
When run, the code outputs:
1 2 3 4 |
Make: Toyota Model: Corolla Year: 2020 |
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:
1 2 3 4 |
with open("car_info.txt", "r") as file: for line in file: print(line, end="") |
When run, the code outputs:
1 2 3 |
Make: Toyota Model: Corolla Year: 2020 |