Python Program To Create And Write To A Text File
Published on October 21 2021
In this tutorial, you will learn how to create a text file, write some data and save the file on a local machine using python.
Methods
Python provides inbuilt function for creating, writing and reading files, so there is no need to import external libraries. We'll see some basics.
- Open method.
- With and Open method
Modes
Modes | Description |
'r' | open for reading (default) |
'w' | open for writing, truncating the file first |
'x' | open for exclusive creation, failing if the file already exists |
'a' | open for writing, appending to the end of file if it exists |
'b' | binary mode |
't' | text mode (default) |
'+' | open for updating (reading and writing) |
Code Explanation
- First step is to create a file. To create a new file in python, we will use the Python open method.
file = open("myfile.txt","w")
The open method accepts many arguments, but most of the time you will only use two.
- File Name
- Specify the full path of the file or if you want to create file in the same directory, just write the file name.
- Mode
- Python provides multiple modes (refer above table). In this example, the file has not been created yet, so will use write (W) mode.
- File Name
- The write method to enter data into the file.
file.write("data inside file.")
- It is always recommended to close the file object using the close method
file.close()
- Run the program.
- “myfile.txt” file will be created with some data.
- Using the above method we have to specifically close the file object. To let Python close file instances automatically, we can use the with method.
We don't have to write a close method and Python will automatically close the file instance.with open("myfile.txt","w") as file: file.write("data inside file.")
- If the filename name or the file path is incorrect, you will get a file not found error.
- To avoid such issues, it is always recommended or as a best practice to write file operation using try-catch block.
try: file=open("myfile.txt","r") except IOError: print("Error : Filename or file path is incorrect.") finally: print("exiting...")
Source Code
# method - 1
file = open("myfile.txt","w")
file.write("data inside file.")
file.close()
# method - 2
with open("myfile.txt","w") as file:
file.write("data inside file.")
# method - 3
try:
file=open("myfile.txt","r")
except IOError:
print("Error : Filename or file path is incorrect.")
finally:
print("exiting...")
Output
"myfile.txt"
data inside file.
Next Tutorial
- Python Program To Create And Write To A Text File
- Python Program To Count Number Of Words In A Text File
- Copy Contents Of One File To Another File In Python
- Python Program To Read A Text File