I'm setting up a function that aims to export data as a text file. The function is called frequently with new data being generated. I'm trying to insert some control logic that handles if exported data already exists or not.
So 1) where text file exists, then append new the data and export. 2) where text file does not exist, create new text file and export.
I've got a try/except call as 99% of the time, the text will already exist.
Where there is no existing text file, the func works fine through the except path. But where there is a text file, both the try and except paths are triggered and I get the export from except.
The specific question I have is how is the except being triggered when the try section is initiated? If try is used, shouldn't the except be obsolete?
def func():
try:
with open("file.txt", 'a+') as file:
data = [line.rstrip() for line in file]
newdata = ['d','e','f']
alldata = data.append(newdata)
with open("file.txt", 'w') as output:
for row in alldata:
output.write(str(row) + '\n')
except:
data = [['a','b','c']]
with open("file.txt", 'w') as output:
for row in data:
output.write(str(row) + '\n')
func()
Intended output:
where the text file does not exist, the output should be:
[['a','b','c']]where the text file does exist, the output should be:
[['a','b','c'],['d','e','f']]
Edit 2:
def func():
try:
with open("file.txt", 'r') as file:
data = [line.rstrip() for line in file]
newdata = ['d','e','f']
data.append(newdata)
with open("file.txt", 'w') as output:
for row in data:
output.write(str(row) + '\n')
except FileNotFoundError:
data = [['a','b','c']]
with open("file.txt", 'w') as output:
for row in data:
output.write(str(row) + '\n')
func()