# Specify the path for the new text file new_file_path = 'new_file.txt' # Content to write to the new file content_to_write = """Hello, world! This is a new text file created with Python. We can add as many lines of text as we wish."""
# Using the with statement to open the file in write mode with open(new_file_path, 'w', encoding='utf-8') as file: # Write the content to the file file.write(content_to_write)
print(f"Content written to {new_file_path}")
The output will be a newly generated new_file.txt in the working directory.
new_file_path
: Replace 'new_file.txt'
with your desired file name or path. If you specify a file name without a directory path, the file will be created in the same directory as your Python script. For a different location, provide the full path.
content_to_write
: This variable contains the text that you want to write to the file. You can modify this string to contain any text you want.
open(new_file_path, 'w', encoding='utf-8')
: This opens (or creates, if it doesn't exist) a file for writing ('w'
). If the file already exists, this mode will overwrite it. The encoding='utf-8'
parameter specifies the file's encoding, which is especially important for text containing special characters.
file.write(content_to_write)
: This writes the string stored in content_to_write
to the file.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.