Python File I/O
Python has several functions for creating, reading, updating, and deleting files.
Opening a File
The open() function is used to open a file. It takes two arguments: the file name and the mode.
There are four different modes for opening a file:
"r"- Read - Default value. Opens a file for reading, error if the file does not exist."a"- Append - Opens a file for appending, creates the file if it does not exist."w"- Write - Opens a file for writing, creates the file if it does not exist."x"- Create - Creates the specified file, returns an error if the file exists.
f = open("demofile.txt", "r")
Reading a File
The read() method is used to read the content of a file.
f = open("demofile.txt", "r")
print(f.read())
Writing to a File
The write() method is used to write to a file.
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
Closing a File
It is a good practice to always close the file when you are done with it.
f = open("demofile.txt", "r")
print(f.read())
f.close()
You can also use the with statement, which will automatically close the file for you.
with open("demofile.txt", "r") as f:
print(f.read())