how to add user input to file and print

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • newbieinpython
    New Member
    • Sep 2012
    • 3

    #1

    how to add user input to file and print

    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.
    ------------------------------------------------

    Code:
    #!usr/local/bin/python3
    f = open('python1/inputter.txt', 'w')
    while True:
    	i = input("Write a sentence:")
    	f.write(i)
    	if i == "":
    		break
    f = open('python1/inputter.txt', 'r')
    f.read()
    for line in f:
    	print(line)
    Last edited by zmbd; Sep 23 '12, 04:23 AM. Reason: Please use the format code <CODE/> button around your posted code.
  • zmbd
    Recognized Expert Moderator Expert
    • Mar 2012
    • 5501

    #2
    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

    Comment

    • newbieinpython
      New Member
      • Sep 2012
      • 3

      #3
      How to add a line in file and print

      Originally posted by zmbd
      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
      Thanks for reponse. But I still don't see you are helping with my problem.

      Comment

      • zmbd
        Recognized Expert Moderator Expert
        • Mar 2012
        • 5501

        #4
        read the documentation I linked for you.

        Comment

        • dwblas
          Recognized Expert Contributor
          • May 2008
          • 626

          #5
          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]
          Last edited by Stewart Ross; Sep 24 '12, 12:42 PM. Reason: Thanks for your response. I have removed comments made about the poster which were off-topic.

          Comment

          Working...