Open In App

Create a New Text File in Python

Creating a new text file in Python is a fundamental operation for handling and manipulating data. In this article, we will explore three different methods to achieve this task with practical examples. Whether you’re a beginner or an experienced developer, understanding these methods will provide you with the flexibility to work with text files in Python.

How to Create a New Text File in Python?

Below, are the ways to Create a New Text File in Python.



Create a New Text File Using open() Function

In this example, below code the open() function to create a new text file named new_file.txt. The file is opened in write mode, and the specified content is written into it. Finally, a success message is printed, confirming the successful creation of the file.




# Using open() function
file_path = "new_file.txt"
 
# Open the file in write mode
with open(file_path, 'w') as file:
    # Write content to the file
    file.write("Hello, this is a new text file created using open() function.")
     
print(f"File '{file_path}' created successfully.")

Output :



Create a New Text File Using Path from pathlib

In this example, in below code the Path class from the pathlib module to represent a file path named new_file_method3.txt. With the file opened in write mode using with statement, it writes the specified content. Finally, it prints a success message indicating the creation of the file at the specified path.




from pathlib import Path
 
# Using Path from pathlib
file_path = Path("new_file_method3.txt")
 
# Open the file in write mode using with statement
with file_path.open('w') as file:
    # Write content to the file
    file.write("Creating a text file using pathlib.")
     
print(f"File '{file_path}' created successfully.")

Output :

Create a New Text File Using the IO Module

In this example, the io.open() function is used to open the file in write mode. It is similar to the built-in open() function but provides additional options, such as specifying the encoding. The file is created with the specified text, and the success message is printed.




import io
 
# Using io.open() function
file_path = "new_file.txt"
 
# Open the file in write mode using io.open()
with io.open(file_path, 'w', encoding='utf-8') as file:
    # Write content to the file
    file.write("This text file is created using io.open() function.")
     
print(f"File '{file_path}' created successfully.")

Output :


Article Tags :