Create a New Text File in Python
Last Updated :
05 Feb, 2024
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.
Python3
file_path = "new_file.txt"
with open (file_path, 'w' ) as 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.
Python3
from pathlib import Path
file_path = Path( "new_file_method3.txt" )
with file_path. open ( 'w' ) as 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.
Python3
import io
file_path = "new_file.txt"
with io. open (file_path, 'w' , encoding = 'utf-8' ) as file :
file .write( "This text file is created using io.open() function." )
print (f "File '{file_path}' created successfully." )
|
Output :
Share your thoughts in the comments
Please Login to comment...