Python open() Built in Function
The open() function is used to open a file and return a file object that can be used to read or write data. The syntax of the open() function is:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
The file parameter is the name of the file or a path to it. The mode parameter specifies how the file should be opened. There are different modes for reading, writing and appending data. Some common modes are:
“r” - Read - Default value. Opens a file for reading, error if the file does not exist
“w” - Write - Opens a file for writing, creates the file if it does not exist
“a” - Append - Opens a file for appending, creates the file if it does not exist
“r+” - Read/Write - Opens a file for both reading and writing, error if the file does not exist
Here are some examples of using the open() function in Python:
To open a text file named “demofile.txt” in read mode and print its content:
f = open("demofile.txt", "r")
print(f.read())
f.close()
To write some text to a new file named “newfile.txt” in write mode:
f = open("newfile.txt", "w")
f.write("Hello world!")
f.close()
To append some text to an existing file named “oldfile.txt” in append mode:
f = open("oldfile.txt", "a")
f.write("\nThis is a new line.")
f.close()
To read only one line from a text file named “oneline.txt” in read mode:
f = open("oneline.txt", "r")
print(f.readline())
f.close()
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment