Posts: 5
Joined: Fri Apr 17, 2015 6:51 pm

Can't write to a file with Python

Fri Apr 17, 2015 7:04 pm

Ill try and get straight to the point.

Here is the code I wrote

Code: Select all

# Grabs a line from user input and saves it to a file
import sys

for line in sys.stdin:
	file = open('notes.txt', 'a')
I tried running this in a python shell and it worked fine. When I try to run this in terminal, it doesn't work. I have tried using python and python3.

Maybe it is something in my code? I haven't used python before, though I have coded for a while using Java/C++

User avatar
Posts: 1820
Joined: Mon Mar 23, 2015 7:39 am
Location: Rochester, MN
Contact: Website

Re: Can't write to a file with Python

Sat Apr 18, 2015 6:17 am

I don't think you want a close() on every write do you??

By running 'in a terminal' do you mean running the python code as a script from the command line?

Where is your shabang line?


... rest of script

You need a shabang line to tell sh or bash or whatever how to run the python interpreter.

Check here:


There are lots of ways to run a python script; interpreted, compiled, from another python script, from another shell script, so on and on... do some reading. Google is our friend.

User avatar
Posts: 3439
Joined: Sat Dec 21, 2013 5:29 pm
Location: USA

Re: Can't write to a file with Python

Sat Apr 18, 2015 12:04 pm

What is your error? One thing I notice off the bat is that you should put the full path to the file in your code.
There are 10 types of people: those who understand binary and those who don't.

Return to “Beginners”