Delete a file with Python

To delete a file with this script, we can use the os module.It’s recommended to check with a conditional if the file exist before calling the remove() function from the module:

import os

if os.path.exists("<file_path>"):

[mai mult...]

Write to a File in Python

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")
[mai mult...]

How to Read Files in Python

it’s recommended to use with statement to work with files because it opens them only while we need them and it closes them automatically.

To read a file, we use this syntax:

with open("<file_path>") as <file_var>:
[mai mult...]