Skip to content

Python create text file

  • by

Use the open() function with “x” or “w” mode to create a new text file in Python. Use file name with txt extensions for a text file.

open('file_Path', 'access_mode')

Create a text file with the command function “x”.

f = open("myfile.txt", "x")

“x” – Create: this command will create a new file if and only if there is no file already in existence with that name or else it will return an error.

f = open("myfile.txt", "w")

“w” – Write: this command will create a new text file whether or not there is a file in the memory with the new specified name. It does not return an error if it finds an existing file with the same name – instead, it will overwrite the existing file.

The + is telling the Python interpreter to open the text file with read and write permissions.

Python creates a text file example

A simple example code creates a new empty text file using the built-in function open().

fp = open('sales.txt', 'x')
fp.close()

fp = open('sales_2.txt', 'w')
fp.write('first line')
fp.close()

Output:

Python create text file example

Create a File In A Specific Directory

To create a file inside a specific directory, we need to open a file using the absolute path. An absolute path contains the entire path to the file or directory that we need to use.

with open(r'E:\rohit\reports\profit.txt', 'w') as fp:
    fp.write('This is first line')
    pass

Create a File with a DateTime

from datetime import datetime

# get current date and time
x = datetime.now()

# create a file with date as a name day-month-year
file_name = x.strftime('%d-%m-%Y.txt')
with open(file_name, 'w') as fp:
    print('created', file_name)

# with name as day-month-year-hours-minutes-seconds
file_name_2 = x.strftime('%d-%m-%Y-%H-%M-%S.txt')
with open(file_name_2, 'w') as fp:
    print('created', file_name_2)

# at specified directory
file_name_3 = r"E:\demos\files_demos\account\\" + x.strftime('%d-%m-%Y-%H-%M-%S.txt')
with open(file_name_3, 'w') as fp:
    print('created', file_name_3)

Do comment if you have any doubts or suggestions on this Python file topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading