Issue
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.
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']]
Solution
def func():
newdata = ['d','e','f']
try:
# Open file to read existing data and then append
with open("file.txt", 'r+') as file:
data = [line.strip() for line in file]
file.seek(0) # Move pointer to the start of the file
if data:
# Convert string representation of list back to list
data = eval(data[0])
else:
# Initialize data if file is empty
data = []
data.append(newdata) # Append new data
file.write(str(data) + '\n') # Write updated data
file.truncate() # Truncate file to current position
except FileNotFoundError:
# Create file and write data if it doesn't exist
with open("file.txt", 'w') as output:
data = [newdata]
output.write(str(data) + '\n')
func()
Answered By - Ayalew Mohammed
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.