Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

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.

Steven Parker
Steven Parker
216,016 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.