python - Writing Data to a .txt File -


i trying write data text file in python , trying user choose name of file string. when comes writing data, shows error.

import random name = input("please enter name: ") clas = input("please enter class in: ") #uses list show 3 operators want use ops = ['+', '-', '*'] #defines 2 variables 1 , 0 x = 1 score = 0 #while variable x less or equal 10, loop continue while x <= 10:     #selects 2 random integers 1 10     num1 = random.randint(1,10)     num2 = random.randint(1,10)     #choses operation list `ops`     operation = random.choice(ops)     #prints 2 numbers , operation in arithmetic question layout     print(num1,operation,num2)     maths = int(eval(str(num1) + operation + str(num2)))     #gets user input there answer question     answer = int(input("what answer  arithmetic question? "))     #if answer user input equal correct answer user scores point , told correct #otherwise, answer must wrong user told score incorrect , no points scored if answer == maths:     print ("correct")     score += 1 else:     print ("incorrect answer") #add 1 onto score while loops depends on make sure loops 10 times x = x + 1 #leaves iteration after 10 loops , prints users final score print ("you scored", score, " out of 10 points") score2 = str(score)     score = str(name + score2 + "\n") open(clas."txt", "a") scorefile: scorefile.write(score)     

to write file:

f = open("filename.txt","w") f.write("writing file!") # writes "writing file!" new line in filename.txt f.close() 

to read file:

f = open("filename.txt","r") lines = f.readlines() f.close() print lines # prints array 

make sure use f.close(), otherwise bad things happen.


Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -