Python Create Text File

Summary: in this tutorial, you’ll learn how to create a new text file in Python using the open() function.

Using the open() function to create a new text file

To create a new text file, you use the open() function. The open() function has many parameters. However, you’ll focus on the first two parameters:

f = open(path_to_file, mode)

The path_to_file parameter specifies the path to the text file that you want to create.

For creating a new text file, you use one of the following modes:

  • 'w' – open a file for writing. If the file doesn’t exist, the open() function creates a new file. Otherwise, it’ll overwrite the contents of the existing file.
  • 'x' – open a file for exclusive creation. If the file exists, it’ll raise an error (FileExistsError). Otherwise, it’ll create the text file.

For example, the following creates a new file called readme.txt and write some text into it:

with open('readme.txt', 'w') as f: f.write('Create a new text file!')
Code language: JavaScript (javascript)

If you don’t want create a new text file in case it already exists, you can use the 'x' mode when calling the open() function:

with open('readme.txt', 'x') as f: f.write('Create a new text file!')
Code language: JavaScript (javascript)

Summary

  • Use the open() function with the 'w' or 'x' mode to create a new text file.
Did you find this tutorial helpful ?