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 Writing to Files

Youssef Moustahib
Youssef Moustahib
7,779 Points

Have I understood this?

Can anyone tell me if I'm on the right page?

Ok so I want to create a new file, I want to name the file "database.txt".

def remember(x): # This is my function
file = open("database.txt", "a") 

I understand that OPEN is the function that creates the file, and "a" basically puts it into append mode, allowing whatever is writtin (the function below) to be be appended to my file called "database.txt"

file.write(x+"\n")
pass

What I dont understand that in workspaces, the variable "file" turns grey when you write it out, almost like it is a special keyword? Whats the word "file" have some importance that I am missing?

Steven Parker
Steven Parker
229,788 Points

It might help to make a snapshot of your workspace and post the link to it here.

1 Answer

John Lack-Wilson
John Lack-Wilson
8,181 Points

Nearly correct, file is not a keyword, but is instead a builtin.

Here's a link to the file builtin. As Steven Parker says it would be useful to make a snapshot of your workspace so we can see exactly the issue. However, I would recommend renaming your variable to something other than file.

Some people use fp as the variable for a file, standing for file pointer.