In this Python file handling, we are going to learn all about how to write an existing file on the server as well as on the local computer. In the previous Python file handling tutorials, we have seen all about how to open a file to read the content from the file.
Note:- To understand this example, you should have basic knowledge of Python programming.
Writing to an existing file
If you have already a file and you want to write to a file then you will need to use the open() function.
- “a”: Append to the end of the file.
- “w”: overwrite the existing content.
Suppose we have a file myfile.txt and we want to append some data.
Hello! Welcome to demofile.txt This file is for testing purposes. Good Luck!
Now we will open the file and add some new content to existing content.
# open file and append some text f = open('myfile.txt','a') f.write(' This file is only for demo purpose') f.close() #open and read file after appending. f = open('myfile.txt','a') f.read() f.close()
Open myfile.txt and overwrite the existing content.
f = open('myfile.txt','w') f.write('This is only for demo purpose') f.close() #open and read file after overwriting. f = open('myfile.txt','a') f.read() f.close()
Create new file
To create a new file in python, use python built-in function open(), with one of the following parameters.
- “x” – Create – will create a file, returns an error if the file exists.
- “a” – Append – will create a file if the specified file does not exist.
- “w” – Write – will create a file if the specified file does not exist.
create a file called “demofile.txt“.
f = open("demofile.txt", "x")
Create a new file if it does not exist.
f = open("mytextfile.txt", "w")
Note:- The “w” mode overwrite the entire data of the file.
In this Python file write tutorial, you have learned all about Python file write operations with the help of examples. Python open is a built-in method that is used to open a file from the server or a local machine to read and write.
In the next python file handling tutorial, we will learn how to delete the existing files from the server using python. If you like the python file write tutorial, please share and keep visiting for further Python tutorials.
Reference:- Click Here