Reputation: 65
How to write a file then read it knowing that I have to write it first because file does not exist when,I use the option 'r+' but I got the error file does not exist.
with open(file,'w') as f:
f.write("")
with open(file,'r') as f:
out = f.read()
Any Solution?
Upvotes: 0
Views: 121
Reputation: 2576
try this code
file = "test.txt"
try:
with open(file, 'r') as f:
print(f.read())
except IOError:
with open(file, 'w') as f:
f.write("")
If file exists
-> The file is read normally by try, and the read result is output.
If the file does not exist
-> Try reading the file, but if it doesn't, an IOError is raised.
-> When an IOError occurs, it writes the file to the filePath immediately
Logic to read after writing file
import os.path
file = 'test.txt'
try:
if not os.path.isfile(file):
with open(file, 'w') as f:
f.write('asd')
with open(file, 'r') as f:
print(f.read())
except IOError:
print('IOError')
Upvotes: 1