CodeGym /Courses /Python SELF EN /Writing Data to a File

Writing Data to a File

Python SELF EN
Level 21 , Lesson 2
Available

3.1 Creating a File

Files are created automatically when opened in write ('w') or append ('a') mode. If the file already exists, write mode 'w' will overwrite its content, while append mode 'a' will add data to the end of the file.

Example of creating a file


file = open('example.txt', 'w')  # Opens the file for writing, creating it if it doesn't exist
file.write("This is a new file.\n")
file.close()
        

In this example, the file example.txt is created (if it doesn't exist) and a line "This is a new file.\n" is written to it.

You can create a completely empty file by opening it for writing and immediately closing it.

Example of creating an empty file


file = open('example.txt', 'w')  
file.close()
        

Note that if you open an existing file for writing, all of its content will be erased.

3.2 Writing to a File

There are two popular methods for writing data to a file — write() and writelines().

The write() Method

The write() method writes a string to a file. If the file is opened in write mode ('w'), its content is erased before new data is written. If opened in append mode ('a'), new data is added to the end of the file.

Example of using write():


# Opening the file in write mode
file = open('example.txt', 'w')
file.write("Hello, World!\n")
file.write("This is a test file.\n")
file.close()
        

The writelines() Method

The writelines() method takes a list of strings and writes them to a file. It doesn't add newline characters automatically, so you need to include them.

Example of using writelines():


lines = ["First line.\n", "Second line.\n", "Third line.\n"]

# Opening the file in write mode
file = open('example.txt', 'w')
file.writelines(lines)
file.close()
        

File Encoding

You can specify the encoding of a text file when reading or writing it. This is done using the named parameter encoding.

Example:


# Opening the file for writing with UTF-8 encoding
file = open('example_utf8.txt', 'w', encoding='utf-8')  
file.write("Text in Russian.\n")
file.write("More text in UTF-8.\n")
file.close()
        

We'll discuss different file and text encodings later, but it's good to know that this parameter exists and using it can save you from many headaches.

3.3 Appending Data to a File

Appending data to the end of a file is as easy as writing it. You just need to specify append mode ('a') when opening the file, and everything else happens automatically.

Here are some examples:

Appending Strings to a File

This example shows how to open a file in append mode ('a') and add several lines to its end.


file = open('example.txt', 'a')  # Opening the file for appending
file.write("This is a new line added to the file.\n")
file.write("Another line is appended.\n")
file.close()  # Closing the file
        

Appending a List of Strings to a File

This example shows how to use the writelines() method to append a list of strings to the end of a file.


lines = [
    "Appending first line from list.\n",
    "Appending second line from list.\n",
    "Appending third line from list.\n"
]
        
file = open('example.txt', 'a')  # Opening the file for appending
file.writelines(lines)  # Appending list of strings
file.close()  # Closing the file
        

Appending a String with Specified Encoding

This example shows how to open a file in append mode with a specified encoding (e.g., UTF-8) and add a line.


# Opening the file for appending with specified encoding
file = open('example_utf8.txt', 'a', encoding='utf-8')  
file.write("Adding a line using UTF-8.\n")
file.write("Another line added.\n")
file.close()  # Closing the file
        

As you can see, it's super simple.

2
Task
Python SELF EN, level 21, lesson 2
Locked
Creating a File
Creating a File
2
Task
Python SELF EN, level 21, lesson 2
Locked
Adding data to a file
Adding data to a file
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION