By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,806 Members | 1,337 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,806 IT Pros & Developers. It's quick & easy.

how to add user input to file and print

P: 3
Here are my code below, i have two issues: 1) user input was overwritten. 2)i don't see the line is printed. What did i miss? please help.
------------------------------------------------

Expand|Select|Wrap|Line Numbers
  1. #!usr/local/bin/python3
  2. f = open('python1/inputter.txt', 'w')
  3. while True:
  4.     i = input("Write a sentence:")
  5.     f.write(i)
  6.     if i == "":
  7.         break
  8. f = open('python1/inputter.txt', 'r')
  9. f.read()
  10. for line in f:
  11.     print(line)
Sep 23 '12 #1
Share this Question
Share on Google+
4 Replies

zmbd
Expert Mod 5K+
P: 5,397
line 2, file opened for write not append.
http://docs.python.org/library/functions.html.
Also between 7 and 8 you do not explicitly close the file... this is highly recommended to do (section 7.2.1 just before 7.2.2): http://docs.python.org/tutorial/inputoutput.html
Sep 23 '12 #2

P: 3
@zmbd
Thanks for reponse. But I still don't see you are helping with my problem.
Sep 23 '12 #3

zmbd
Expert Mod 5K+
P: 5,397
read the documentation I linked for you.
Sep 23 '12 #4

Expert 100+
P: 626
Note that
f.write(i)
sends the data to the buffer to be written to file at some future time as it is more efficient to read or write a group of records at once. Also, the file will have zero length (no data) when you read it because the end-of-file pointer is generally updated when the file is closed and you never close the file. So you have to explicitly close the file which will flush the buffers and update to the correct length. Also, to print the contents you should use
print f.read()
A link to an on-line book on file handling and the use of readlines() plus iterating over the file. [edited to remove off-topic comments]
Sep 23 '12 #5

Post your reply

Sign in to post your reply or Sign up for a free account.