Skip to main content

How to write to a text file in Python

How to write to a text file in Python.

Here is a detailed step-by-step tutorial on how to write to a text file in Python.

Step 1: Opening the File

To write to a text file, you need to first open it in write mode using the open() function. This function takes two parameters: the name of the file and the mode in which you want to open it. In this case, we use the mode 'w' to indicate write mode.

file = open("example.txt", "w")

Step 2: Writing to the File

Once the file is open in write mode, you can use the write() method to write content to the file. This method takes a string as a parameter and writes it to the file.

file.write("Hello, World!")

You can also write multiple lines by using the newline character \n.

file.write("Line 1\n")
file.write("Line 2\n")

Step 3: Closing the File

After you finish writing to the file, it's important to close it using the close() method. This will free up system resources and ensure that the changes are saved.

file.close()

It is a good practice to always close the file when you are done with it.

Complete Example

Here is a complete example that demonstrates how to write to a text file:

# Step 1: Open the file in write mode
file = open("example.txt", "w")

# Step 2: Write content to the file
file.write("Hello, World!\n")
file.write("Line 1\n")
file.write("Line 2\n")

# Step 3: Close the file
file.close()

Make sure to replace "example.txt" with the actual name of the file you want to write to.

Conclusion

By following these steps, you can easily write content to a text file in Python. Remember to open the file in write mode, use the write() method to write content, and close the file when you are done.