How to create a new text file in python:
This post will show you how to create a new text file in Python. With this post, you will learn how to use the open method in Python and its parameters.
open() function:
open function is used to open a file for reading or writing in Python. This function takes different parameters, but we will consider first two parameters: file and mode.
file is a path-like object that defines the path of the file that we want to open. It can be a absolute path or path relative to the current directory.
mode is the file open mode. Following are the available modes for open:
- r: This mode is used to open a file for reading. This is the default mode. It throws an error if the file doesn’t exists.
- w: This mode is used to open a file for writing. If the file doesn’t exists, it creates a file. It truncates the file first.
- a: It is used to open a file for appending. If the file doesn’t exists, it creates a new file.
- x: It opens the file for exclusive creation. It creates the file and if it already exists, it throws one error.
- b: It opens the file in binary mode.
- t: It opens in text mode. This is the default mode.
- +: It is used to open for updating the file (reading and writing).
Create a new text file in Python:
As you can see above, we have different types of modes to use with open. We can use a, w or x to create a new text file:
By using x:
x throws an exception if the file already exists. The below program will create one new text file if it doesn’t exist:
try:
f = open('readme.txt', 'x')
f.write('Hello World !!')
f.close()
except FileExistsError:
print('File already exists')
If the file already exists, it throws one error.
By using a:
try:
f = open('readme.txt', 'a')
f.write('Hello World !!')
f.close()
except:
print('Exception thrown')
It will create the file if it doesn’t exist. Else, it will open the file and append the text to the end of the file.
By using w:
try:
f = open('readme.txt', 'w')
f.write('Hello World !!')
f.close()
except:
print('Exception thrown')
It will create the file if it doesn’t exist. Else, it will open the file and write the content in the file from start.