Python: The Basics and Examples of Writing Files

When performing file operations in Python, the open function is generally used. By using this function, you can open a specified file, read its content, or write new content.

Let’s look at how to write to a text file in Python.

How to Write to a Text File in Python

Basic Method of Writing Data to a File

As seen above, the write method is used to write data to a file. Here, we’ll explain its detailed usage.

1f = open('test.txt', 'w')
2f.write('Hello, Python!\n')
3f.write('Welcome to file handling in Python.')

This code writes two lines of text to a file named test.txt.

How to Append Text to a File

To append new text to the end of a file, use ‘a’ mode.

1f = open('test.txt', 'a')
2f.write('\nAdditional text.')

This code adds Additional text. as a new line to test.txt.

How to Specify File Paths and Current Directory

When opening a file, you need to specify its location (path) correctly. If you don’t specify a path, Python will look in the current directory (current working directory).

1f = open('/path/to/your/file/test.txt', 'w')

The above code specifies that test.txt is in the /path/to/your/file/ directory.

Tips and Techniques Related to File Writing in Python

Let’s introduce some tips and techniques when operating files in Python.

Advantages of Using the print Function Over the write Method

You can also use the print function instead of the write method to write to a file. When using the print function, a newline is automatically added after the string, so you don't need to add \n each time.

1f = open('test.txt', 'w')
2print('Hello, Python!', file=f)
3print('Welcome to file handling in Python.', file=f)