0
def function(score,name):
    sumOfStudent = (name + ' scored ' + str(score))
    f = open('test.txt', 'wb')
    f.write(sumOfStudent)
    f.close()

user_name = input("Please enter yout full name: ")
user_score = int(input("Please enter your score: "))

function(user_score,user_name)

f = open('test.txt')
print(f.read())
f.close()

I was writing a simple program in python which allowed the user to enter information and then for that text to be stored in a .txt file. This worked however it would always write to the same line, I was wondering how I would make the f.write(sumOfStudent) on a new line every time (sumOfStudent is the variable to hold user input) Thanks!

4
  • 1
    end with a newline. f.write(sumOfStudent + "\n") Commented Dec 10, 2014 at 16:33
  • 5
    You are opening the file in 'w' (overwrite) mode, rather than 'a' (append). Commented Dec 10, 2014 at 16:33
  • @AdamSmith Thanks for the help! Can't believe it was that simple. Commented Dec 10, 2014 at 16:40
  • @jonrsharpe Thanks as well, not sure why I was using 'wb' mode! Commented Dec 10, 2014 at 16:41

1 Answer 1

2

Hey what you are doing is not writing to the end of the file you are overwriting everytime 'w' what you need to be doing is appending it to the file by using 'a'

f = open('test.txt', 'a')

Also to write to a new line you must tell the program thats what you're doing by declaring a new line "\n"

f.write(sumOfStudent + "\n")
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh I see the comments above have already fixed your problem :) sorry for my late answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.