简体   繁体   中英

Writing text (from a variable) into a file and on a new line in Python

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!

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM