Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Reading from Files

Elise Gordillo
Elise Gordillo
1,601 Points

Index error

Iā€™m getting an index error with the following code:

import sys

def rememberer(thing): #open file #input("What should I remember? ") with open("mylist.txt", "a") as file: #write file file.write(thing + "\n")

def show(): with open("mylist.txt") as file: for line in file: print(line)

if name == 'main': if sys.argv[1].lower() == '--list': show() else: rememberer(' '.join(sys.argv[1:]))

2 Answers

Steven Parker
Steven Parker
229,005 Points

Python is particularly hard to read without blockquoting, but the only indexing I see is where you check the invocation line using sys.argv[1]. I'm guessing when you ran the program you didn't add any arguments to the command line.

You should probably test the length of argv before accessing the second item.

Elise Gordillo
Elise Gordillo
1,601 Points

I wrote the program in PyCharm. I didn't realize when I was watching the lesson that this is something that could only be run from the terminal. I've rewritten the program and taken out the sys.argv line. I wish there was more clarification on the videos when something will only work from command line.