How to create a new text file using Python
Categories:
Creating and Writing to Text Files in Python

Learn the fundamental methods for creating new text files, writing content to them, and managing file operations in Python 2.7.
Working with files is a common task in programming, and Python provides straightforward ways to handle file I/O (Input/Output). This article will guide you through the process of creating new text files and writing data to them using Python 2.7. We'll cover basic file opening modes, writing strings, and ensuring proper file closure.
Understanding File Modes
When you open a file in Python, you need to specify a 'mode' that dictates how the file will be accessed. For creating and writing to text files, the most common modes are 'w' (write) and 'a' (append). Understanding the difference is crucial to avoid unintended data loss.
flowchart TD A[Start File Operation] --> B{Choose File Mode} B --> |'w' (Write)| C[Create/Overwrite File] C --> D[Write Content] B --> |'a' (Append)| E[Open Existing/Create New] E --> F[Append Content to End] D --> G[Close File] F --> G
Flowchart of Python file opening modes for writing
Creating and Writing with 'w' Mode
The 'w' mode is used to open a file for writing. If the file does not exist, Python will create it. If the file already exists, its contents will be erased, and new data will be written from the beginning. After writing, it's essential to close the file to ensure all data is saved and resources are released.
# Open a file in write mode ('w')
# If 'my_new_file.txt' doesn't exist, it will be created.
# If it exists, its content will be truncated.
file_object = open('my_new_file.txt', 'w')
# Write a string to the file
file_object.write('Hello, Python file handling!\n')
file_object.write('This is a new line.\n')
# Close the file to save changes
file_object.close()
print "'my_new_file.txt' has been created and written to."
Example of creating and writing to a file using 'w' mode
Appending to an Existing File with 'a' Mode
If you want to add content to the end of an existing file without overwriting its current data, the 'a' (append) mode is what you need. If the file doesn't exist, Python will create it, just like with 'w' mode. New content will always be added at the end of the file.
# First, let's ensure the file exists with some content
with open('my_append_file.txt', 'w') as f:
f.write('Initial content.\n')
# Now, open the file in append mode ('a')
# New content will be added to the end.
file_object = open('my_append_file.txt', 'a')
# Append new strings to the file
file_object.write('This line is appended.\n')
file_object.write('Another appended line.\n')
# Close the file
file_object.close()
print "'my_append_file.txt' has been appended to."
Example of appending content to a file using 'a' mode
with
statement. This ensures that files are automatically closed even if errors occur, preventing resource leaks and data corruption. While the examples above use explicit close()
, the with
statement is the preferred modern approach.# Using 'with' statement for automatic file closing
file_name = 'my_safe_file.txt'
# Write mode with 'with'
with open(file_name, 'w') as f:
f.write('This is written using the with statement.\n')
f.write('It ensures the file is closed automatically.\n')
print "'my_safe_file.txt' created and written using 'with'."
# Append mode with 'with'
with open(file_name, 'a') as f:
f.write('This content is appended safely.\n')
print "'my_safe_file.txt' appended using 'with'."
Using the with
statement for safer file operations
Writing Multiple Lines and Other Data Types
Beyond simple strings, you might need to write lists of strings or convert other data types to strings before writing them to a file. The writelines()
method is useful for writing a list of strings, and remember that all data must be converted to a string before writing to a text file.
file_name = 'data_file.txt'
# Writing a list of strings
lines_to_write = [
'First item in the list.\n',
'Second item, followed by a number: ' + str(123) + '\n',
'Third item, a float: ' + str(3.14159) + '\n'
]
with open(file_name, 'w') as f:
f.writelines(lines_to_write)
f.write('This line was added separately.\n')
print "'data_file.txt' created with multiple lines and mixed data types."
Writing lists of strings and converted data types to a file
1. Choose a File Mode
Decide whether you want to create/overwrite ('w') or append ('a') to the file. This is the most critical decision to prevent data loss.
2. Open the File
Use open('filename.txt', 'mode')
to get a file object. For best practice, use the with open(...) as f:
syntax.
3. Write Content
Use file_object.write('your string\n')
for single strings or file_object.writelines(list_of_strings)
for multiple lines. Remember to include newline characters (\n
) for line breaks.
4. Close the File (if not using with
)
If you didn't use the with
statement, explicitly call file_object.close()
to save changes and release the file handle.