Write to a File in Python

Configurare noua (How To)

Situatie

To replace the content completely, we use the "r" mode, so we pass this string as the second argument to open(). We call the .write() method on the file object passing the content that we want to write as argument.

For example:

words = ["Blue", "Amazing", "Python", "Code"]

with open("famous_places.txt", "r") as file:
    for word in words:
        file.write(word + "\n")

Backup

When you run the program, a new file will be created.

This will be the content of the file:

Blue
Amazing
Python
Code

Solutie

Pasi de urmat

However, if you want to append the content, then you need to use the "a" mode:

with open("<file_path>", "a") as <file_var>:
    <code>

For example:

words = ["Blue", "Amazing", "Python", "Code"]

with open("famous_quotes.txt", "a") as file:
    for word in words:
        file.write(word + "\n")

This change will keep the existing content of the file and it will add the new content to the end. If we run the program again these strings will be added to the end of the file:

Blue
Amazing
Python
Code Blue
Amazing
Python
Code

Tip solutie

Permanent

Voteaza

(6 din 8 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?