Creating and writing to a text file in Python is straightforward. Here's a simple guide to help you get started:

1. Opening a File

To create and write to a text file, you need to open it using Python's built-in open() function. The open() function takes two main arguments:

  • The name of the file.
  • The mode in which you want to open the file (e.g., 'w' for writing, 'a' for appending).
file = open("example.txt", "w")
  • "example.txt" is the file name.
  • "w" mode stands for "write." If the file doesn't exist, Python will create it. If it does exist, it will overwrite the content.

2. Writing to the File

Once the file is opened in write mode, you can write to it using the write() method.

file.write("Hello, this is a sample text.")

This line writes the string "Hello, this is a sample text." into example.txt.

3. Closing the File

After writing to the file, it’s important to close it to ensure the data is saved and to free up system resources.

file.close()

Alternatively, you can use the with statement to handle file opening and closing automatically:

with open("example.txt", "a") as file:
    file.write("\nThis is an additional line.")

This approach is cleaner because the file is automatically closed when the block inside the with statement is exited.

4. Appending to a File

If you want to add content to an existing file without overwriting it, you can use the append mode "a":

5. Reading from a File

If you later want to read from the file, you can open it in read mode "r":

with open("example.txt", "r") as file:
    content = file.read()
    print(content)

This will print the content of example.txt to the console.

By following these steps, you can easily create, write, append, and read from text files in Python.

Simon

102 Articles

I love talking about tech.