Hi guys welcome back to another interesting session on this platform. Today we are going to see how we can write and create files in python. If you are new in this platform, please do checkout our previous articles and also subscribe to our YouTube channel for the video tutorials.
Creating text files in python is quite easy. We have learned how to open and read a file. Let’s now try writing into a file.
They are two main ways of writing into a file which are
- ‘a’ (append) mode
- ‘w’ mode. When you use this mode, you will erase or delete all the previous content that is exiting in the file.
Let’s take an example with both cases
f = open (“myfile.txt”, “a”)
f.write(“python is really awesome”)f.write(“python is fun”)f.close()
When the above program is executed, the compiler will ask you to save the file by specifying the name of the new file you are creating. In our case we saved it as myfile.
The write function() is being used here, so that we can append the two sentences ‘python is really awesome’ and ‘python is fun’ to a file, with each file starting on a new line.
Using the second method
With open(“myfile.txt”, “w”)
f.write(“\npython is my favorite programming language”)f.write(“\npython is cool”)f.close()
Result.
When you run the code, the compiler will ask you to name the file which you want to run. I saved it as python
When you open the folder (folder’s name is python), we see the result of our program
We use the
“x” - Create - will create a file and return an error if the file exist
“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
“r” - This a default mode. It open files for reading.
“t” - This is a default mode. It open files in text mode
“b” - Its creates files in binary mode
“+” - This open files for reading and writing
Thanks for reading guys. Hope you had a nice time coding.
It 's an amazing and awesome blog
ReplyDeletePython Online Training In Hyderabad
Python Online Training