How do you append and read a file in python?

'r' will read a file, 'w' will write text in the file from the start, and 'a' will append. How can I open the file to read and append at the same time?

I tried these, but got errors:

open("filename", "r,a")

open("filename", "w")
open("filename", "r")
open("filename", "a")

error:

invalid mode: 'r,a'

How do you append and read a file in python?

TrebledJ

8,1027 gold badges23 silver badges46 bronze badges

asked May 30, 2019 at 15:19

How do you append and read a file in python?

1

You're looking for the r+ or a+ mode, which allows read and write operations to files (see more).

With r+, the position is initially at the beginning, but reading it once will push it towards the end, allowing you to append. With a+, the position is initially at the end.

with open("filename", "r+") as f:
    # here, position is initially at the beginning
    text = f.read()
    # after reading, the position is pushed toward the end

    f.write("stuff to append")
with open("filename", "a+") as f:
    # here, position is already at the end
    f.write("stuff to append")

If you ever need to do an entire reread, you could return to the starting position by doing f.seek(0).

with open("filename", "r+") as f:
    text = f.read()
    f.write("stuff to append")

    f.seek(0)  # return to the top of the file
    text = f.read()

    assert text.endswith("stuff to append")

answered May 30, 2019 at 15:39

How do you append and read a file in python?

You can't do that with a textfile. Either you want to read it or you want to write to it. The a or the r specifies a seek to a particular location in the file. Specifying both is asking open to point to two different locations in the file at the same time.

Textfiles in general can't be updated in place. You can use a to add new stuff to the end but that is about it. To do what I think you want, you need to open the existing file in read mode, and open another, new file in write mode, and copy the data from the one to the other.

After that you have two files so you have to take care of deleting the old one. If that is troublesome, take a look at the module in-place.

The other alternative is to read the input file into memory, close and reopen it for writing, then write out a new version of the file. Then you don't have to delete the old copy. But if something goes wrong in the middle you will have no old input file, because you deleted it, and no new output file either, because you didn't successfully write it.

The reason for this is that textfiles are not designed for random access.

answered May 30, 2019 at 15:28

How do you append and read a file in python?

BoarGulesBoarGules

15.9k2 gold badges29 silver badges42 bronze badges

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    While reading or writing to a file, access mode governs the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. The definition of these access modes is as follows:

    • Append Only (‘a’): Open the file for writing.
    • Append and Read (‘a+’): Open the file for reading and writing.

    When the file is opened in append mode in Python, the handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data. 

    Example 1: Python program to illustrate Append vs write mode.

    Python3

    file1 = open("myfile.txt", "w")

    L = ["This is Delhi \n", "This is Paris \n", "This is London"]

    file1.writelines(L)

    file1.close()

    file1 = open("myfile.txt", "a"

    file1.write("Today \n")

    file1.close()

    file1 = open("myfile.txt", "r")

    print("Output of Readlines after appending")

    print(file1.read())

    print()

    file1.close()

    file1 = open("myfile.txt", "w"

    file1.write("Tomorrow \n")

    file1.close()

    file1 = open("myfile.txt", "r")

    print("Output of Readlines after writing")

    print(file1.read())

    print()

    file1.close()

    Output:

    Output of Readlines after appending
    This is Delhi
    This is Paris
    This is LondonToday
    
    
    Output of Readlines after writing
    Tomorrow

    Example 2:  Append data from a new line

    In the above example of file handling, it can be seen that the data is not appended from the new line. This can be done by writing the newline ‘\n’ character to the file. 

    Python3

    file1 = open("myfile.txt", "w")

    L = ["This is Delhi \n", "This is Paris \n", "This is London"]

    file1.writelines(L)

    file1.close()

    file1 = open("myfile.txt", "a")

    file1.write("\n")

    file1.write("Today")

    file1.write("Tomorrow")

    file1 = open("myfile.txt", "r")

    print("Output of Readlines after appending")

    print(file1.read())

    print()

    file1.close()

    Output:

    Output of Readlines after appending
    This is Delhi
    This is Paris
    This is London
    TodayTomorrow
    

    Note: ‘\n’ is treated as a special character of two bytes.

    Example 3:  Using With statement  in Python

    with statement is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Unlike the above implementations, there is no need to call file.close() when using with statement. The with statement itself ensures proper acquisition and release of resources. 

    Python3

    L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]

    with open("myfile.txt", "w") as file1:

        file1.write("Hello \n")

        file1.writelines(L)

    with open("myfile.txt", 'a') as file1:

        file1.write("Today")

    with open("myfile.txt", "r+") as file1:

        print(file1.read())

    Output:

    Hello
    This is Delhi
    This is Paris
    This is London
    Today

    Note: To know more about with statement click here.


    Can you append a file in Python?

    In order to append a new line your existing file, you need to open the file in append mode , by setting "a" or "ab" as the mode. When you open with "a" mode , the write position will always be at the end of the file (an append).

    How do you read a file in Python?

    To read a text file in Python, you follow these steps: First, open a text file for reading by using the open() function. Second, read text from the text file using the file read() , readline() , or readlines() method of the file object. Third, close the file using the file close() method.

    Which mode opens the file in read and append mode?

    There are many modes for opening a file:.
    r - open a file in read mode..
    w - opens or create a text file in write mode..
    a - opens a file in append mode..
    r+ - opens a file in both read and write mode..
    a+ - opens a file in both read and write mode..
    w+ - opens a file in both read and write mode..

    Can you write and read a file in Python?

    Python provides inbuilt functions for creating, writing, and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s, and 1s).