control flow logic for creating new file

100 Views Asked by At

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:

  1. where the text file does not exist, the output should be:

    [['a','b','c']]

  2. 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()
1

There are 1 best solutions below

2
Moaybe On
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()