I want to get a list that exists in the Python function.

Asked 2 years ago, Updated 2 years ago, 109 views

import sys
import os


def get_fruit_list(fruit_list):

     fruit_path = os.getcwd() + '\\fruit_list.txt'

    try:
        fruits = open(fruit_path, 'r')
        fruit_love = fruits.readlines()
        for fi in fruit_love:
            fruit_list.append(fi)

    except FileNotFoundError:
            fruit_list = ["Apple", "Grape", "Banana"]


aaa = []
get_fruit_list(aaa)
print(aaa)

The get_fruit_list function opens the fruit_list.txt file and saves it as a list. If the file does not exist, use the fixed fruit_list = ['Apple', 'Grape', 'Banana'] list.

If the fruit_list.txt file exists, it imports the data in the txt file into the list without any problems. But there is no data in the list when the file does not exist.

In Faicham, fruit_list = ['Apple', 'Grape', 'Banana'] says fruit_list is a meaningless variable, so how do I get that data into the main function?

python function list

2022-09-22 19:43

2 Answers

except OSError:
        fruit_list.append('Apple')
        fruit_list.append('Grape')
        fruit_list.append('banana')

Do not create variables as in the body, but call the append method immediately as above

Python, unlike c, does not have reference operators such as &. The list is, of course, passed as a reference, but fruit_list = [] creates a new regional variable.


2022-09-22 19:43

https://docs.python.org/3/library/functions.html#open

Click the link above to view the document

Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.

That's what it says.

This means that the exception processing is invalid.

Please process OSError, not FileNotFoundError.


2022-09-22 19:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.