DEV Community

importox
importox

Posted on

How to write in an existing file in Python?

You are going to learn how to write text in an existing file in python?

Python can work with files, it can read files, write file and even read csv files. In brief, any data can be read by Python.

You can use the open(filename,mode) function to open a file. There are a set of file opening modes.

To write in an existing file you have to open the file in append mode("a") , if the file does not exist, the file will be created.

To write text in an existing file , first step is to verify if the file exists or not?

If the file you want to write to does not exist, program will create a new file.

append to file

In this Python example, it creates a file, write a string and then closes the file. After that, you will open the file in append mode "a" .

    # write lines to an existing file
    # after creating it    
    fo = open("example1.txt", "w")
    fo.write("Hello world.")
    fo.close()

Now that you have a file, you can append to it

    # open the file in append mode
    fo = open("example1.txt","a")
    fo.write("I like Python")
    fo.close()

If you want you can read and display it

    # read and display the file 
    fo = open("example1.txt","r")
    print("The file contains: ")
    dummy = fo.read()
    print(dummy)   
    fo.close()

The program above outputs this:

The file contains: 
Hello world.I like Python 

This works in both the Python shell and running from a file.

Oldest comments (2)

Collapse
 
michaelcurrin profile image
Michael Currin • Edited

Can I suggest rewriting to use the more Pythonic syntax?

with open('foo.txt', 'a') as f_out:
    f_out.write('Hello')
Enter fullscreen mode Exit fullscreen mode

Most code uses the with block as it is fewer lines, it's a well-known pattern and its safer - the file always closes regardless of error or if your forget to add .close so it controls memory.

You can also do fancy things like open a file to read and different file to read, in one with statement.

Collapse
 
jarvissilva profile image
Jarvis Silva

Here is more detailed tutorial Creating file in python if not exisits