Knut Knutson
Knut Knutson

Reputation: 163

Getting IOError trying to open file through Kivy

I'm writing an app that opens a csv file and lays out the data with Kivy. The csv file is stored in the same folder as main.py.

class BeerCellar(ScrollView):
    def __init__(self, **kwargs):
        super(BeerCellar, self).__init__(**kwargs)
        self.beer_list = []
        with open(os.path.join('beer_archive.csv'), 'rb', 1) as beer_csv:
            beer_reader = csv.DictReader(beer_csv)
            for beer in beer_reader:
                beer_list.append(beer)

I'm able to open the csv file using IDLE, but when I right click main.py and select 'send to: Kivy 1.7.0' as Kivy is loading it up I get the following error:

    File "C:\Users\Knute\Python\projects\Kivy_Stuff\Cellar\main.py", line 34, in
__init__
    with open(os.path.join('beer_archive.csv'), 'rb', 1) as beer_csv:
IOError: [Errno 2] No such file or directory: 'beer_archive.csv'

The file permissions are set to read/write for all.
Using Windows 7, Python 2.7

Upvotes: 1

Views: 745

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123042

The file beer_archive.csv does not exist in your present working directory, which is most likely the C:\Users\Knute\Python\projects\Kivy_Stuff\Cellar folder.

Without a full path, Python looks in the current working directory, and what that is depends on the way your program was started and if any calls to os.chdir() were made to change the current working directory.

Use a full path to your archive file:

with open(os.path.join(folder_path, 'beer_archive.csv'), 'rb', 1) as beer_csv:

where folder_path is set to the full path of the folder where beer_archive.csv is located.

Note that you can save yourself a loop if all you do is append the rows from your CSV to self.beer_list; the following will do that in one command:

class BeerCellar(ScrollView):
    def __init__(self, **kwargs):
        super(BeerCellar, self).__init__(**kwargs)
        with open(os.path.join(folder_path, 'beer_archive.csv'), 'rb', 1) as beer_csv:
            self.beer_list = list(csv.DictReader(beer_csv))

Upvotes: 1

Related Questions