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

Daniel Petrov
Daniel Petrov
3,495 Points

File not created

The file was not created. I made one manually but still nothing was written in it. Any idea why? I am on OSX. I have done other exercises where databases were created in the same folder and info written in but file.write() doesn't work for some reason. Tried with sudo or specifying the whole path with no success.

Cindy Lea
Cindy Lea
Courses Plus Student 6,497 Points

Without seeing code...it mau be a file permission deal...

2 Answers

Kristian Gausel
Kristian Gausel
14,661 Points

Writing a file in python should be done like this:

with open("filepath", "w") as f:
    f.write("file content")

If this is similar to what you have done, then it is a permission thing. Try doing it in a different folder.

Daniel Petrov
Daniel Petrov
3,495 Points

Yes, this is the code I used. At the end it just I worked somehow. Thanks for your replies, anyway! Kristian Gausel and Cindy Lea