创建新文件的控制流逻辑

问题描述 投票:0回答:1

我正在设置一个旨在将数据导出为文本文件的函数。该函数被频繁调用并生成新数据。我正在尝试插入一些控制逻辑来处理导出的数据是否已存在。

所以1)文本文件存在的地方,然后追加新数据并导出。 2) 如果文本文件不存在,则创建新文本文件并导出。

我有一个 try/ except 调用,因为 99% 的情况下,文本已经存在。

在没有现有文本文件的情况下,该函数可以通过 except 路径正常工作。但是,如果有文本文件,则 try 和 except 路径都会被触发,并且我会从 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()

预期输出:

  1. 当文本文件不存在时,输出应为:

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

  2. 如果文本文件确实存在,输出应该是:

    [['a','b','c'],
    ['d','e','f']]

python try-except
1个回答
1
投票
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()
© www.soinside.com 2019 - 2024. All rights reserved.