Python Unleashed: Unlock the Potential of Programming — File Input and Output
Chapter 7
Introduction
File Input and Output (I/O) is a way for a program to read data from a file or write data to a file. In Python, you can use the built-in open()
function to work with files. The open()
function takes a filename as its first argument and a mode as its second argument. The mode specifies whether the file should be opened for reading ('r'), writing ('w'), or appending ('a').
Here is an example of how to open a file for reading:
f = open('myfile.txt', 'r')
And here is an example of how to open a file for writing:
f = open('myfile.txt', 'w')
When you’re done working with a file, you should close it using the close()
method:
f.close()
It’s worth mentioning that you can use the with
statement to open files, this will take care of closing the file after you're done using it.
with open('myfile.txt', 'r') as f:
# do something with the file
Reading from Files
Once a file is opened for reading, you can read its contents using the read()
method. The read()
method reads the entire contents of the file and…