Python write() Function
Note - The w mode is for writing, whereas the a mode is for appending.
Python write() Syntax
The syntax to use write() function in a Python program is:
where fo indicates to the file object or handler, and string_to_write is the string or text that has to be written in the file whose handler is fo.
Python write() Example
The program given below uses write() function to write some texts say Hey! My name is Michael Smith to a file say codescracker.txt. Before writing to the file, we need to open the file, so here I've used w opening mode.
Because I've used w opening mode, therefore if the file codescracker.txt is not available in the current directory, then the file automatically gets created and the content gets written in it. Otherwise, if file is available, then the content gets overwritten or previous content gets deleted and this new content gets written. Let's see how.
fo = open("codescracker.txt", "w") fo.write("Hey! My name is Michael Smith") print("The content written in the file.") fo.close()
If you execute this program, then the output produced will be:
Now if you open the current directory, then this file with same content will be available. Here is the snapshot of the file that is created using the above program in my case:
Now let's create another program, that demonstrates all about write() function in single Python program. This program is created, so that, the name of file gets received by user, at run-time of the program.
print("Enter File's Name: ", end="") filename = input() print("\n1. Write Content.") print("2. Append Content.") print("Enter Your Choice (1 or 2): ", end="") choice = int(input()) if choice == 1: fo = open(filename, "w+") print("\nEnter the content to write: ", end="") content = input() fo.write(content) print("\n----Content of File----") fo.seek(0) print(fo.read()) fo.close() elif choice == 2: fo = open(filename, "a+") print("\nEnter the content to append: ", end="") content = input() fo.write("\n") fo.write(content) print("\n----Content of File----") fo.seek(0) print(fo.read()) fo.close() else: print("\nInvalid Input!")
Here is its sample run with user input codescracker.txt as name of file, 2 as choice, and This is a tutorial on write() Function. as content:
The following statement:
is used to move the file handler at the beginning of the file to read all the content from start to end. To learn in detail about seek(), refer to its separate tutorial.
And the statement:
is used to append the content from newline.
« Previous Function Next Function »
Follow/Like Us on Facebook
Subscribe Us on YouTube