Search code examples
pythonpython-3.xfilefile-read

Does python have a file opening mode which combines the features of "w+" and "r"?


I have a script which I use for requesting data from an external API. My script contains complex logic and describing it will take much time. At a certain point of my script I need to open a file, loop over it and and extract each value from it.

with open(os.path.abspath("/data/data/com.termux/files/home/storage/forecast/endpoints/leagueIdExtracted.txt"), "r+") as leagueIdExtracted:
    print("Check is file {} was opened".format(leagueIdExtracted))                                                        
    for id in leagueIdExtracted:
        print("ID {} from opened file".format(id))                 
        savedLeagues.add(int(str(id[:-1])))                 
        print("League IDs {} from file which contain alredy requested IDs".format(savedLeagues))

But sometimes isn't up to me file which i open in above isn't exist

with open(os.path.abspath("/data/data/com.termux/files/home/storage/forecast/endpoints/leagueIdExtracted.txt"), "r+") as leagueIdExtracted:

Because of it while I open this file I have to open it in "w+" mode. Opening it in "w+" guarantees that a non-existing file will be created and opened. But while my script opened the file in "w+" mode it can't extract values from it.

for id in leagueIdExtracted:
    print("ID {} from opened file".format(id))                 
    savedLeagues.add(int(str(id[:-1])))

Because of it I have to manually switch between "w+" and "r" modes. Can anyone advise me whether Python has a mode which will create file while opening it if it does not exist as "w+" mode and also allow to extract data as "r" mode?


Solution

  • You can use a+ as a mode. Using a+ opens a file for both appending and reading. If the file doesn't exist, it will be created.

    # In this example, sample.txt does NOT exist yet
    with open("sample.txt", "a+") as f:
        print("Data in the file: ", f.read())
        f.write("wrote a line")
    print("Closed the file")
    
    with open("sample.txt", "a+") as f:
        f.seek(0)
        print("New data in the file:", f.read())
    

    Output:

    Data in the file:
    Closed the file
    New data in the file: wrote a line
    

    You should keep in mind that opening in a+ mode will place the cursor at the end of the file. So if you want to read data from the beginning, you will have to use f.seek(0) to place the cursor at the start of the file.