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?

Upvotes: 1

Views: 69

Answers (2)

CypherX
CypherX

Reputation: 7353

You want to use 'r+' if your objective is to read/write to existing files. In case you want to create new file as well, use 'a+'. In other words you will be able to do all of the follwing three.

1. Create if file does not exist
2. Write (append) if file exists
3. Read in file

Quoting from Reading and Writing Files: Python Documentation:

  • 'r' when the file will only be read,
  • 'w' for only writing (an existing file with the same name will be erased),
  • 'a' opens the file for appending; any data written to the file is automatically added to the end.
  • 'r+' opens the file for both reading and writing.

Upvotes: 1

SyntaxVoid
SyntaxVoid

Reputation: 2633

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.

Upvotes: 3

Related Questions