Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

saving data to txt file using python

I am new in python, and I really need some help. I am doing this memory game where I need to save user, game score and time into a text file using python. I have tried several ways to do it, but nothing seems to work. I need to get the text what is shown after game on html page (statsParagraph) into *txt file using python In my html code I have this:

<form  action="http://....python file addres" method="GET">
<p id="statsParagraph" name="user" value=""></p>
</form>

in my javascript code I have this:

function showstatistic(){ 
var user = prompt ("What is your name?","");
alert (user + ". game is over!")
var s="";
for(var i=0;i<statistic.length;i++){
    var t=statistic[i].time;
    var timeString= (t-(t%60))/60+":"+(t%60);
    s += "User: " + user 
    +" <br/>"
    + " Game #"+ (i+1) +"  "
    +" <br/>"
    +" Guessed: "+ statistic[i].guessed
    +" <br/>"
    +" Minus points: "+ statistic[i].minuses
    +" <br/>"
    +" Guessed right: "+ statistic[i].plusPoints
    +" <br/>"
    +" Time: "+ timeString
    +" <br/>"
    +" <br/>";
    }   
$("#statsParagraph").html(s);
}   
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You would open the code with

from sys import argv

script, filename = argv

target = open(filename, 'w')

then assign each piece of info to a variable with an appropriate name

time = #x
score = #x
user = #name

then type the following

target.write(time)
target.write("
")
target.write(score)
target.write("
")
target.write(user)
target.write("
")

target.close()

when you run the file you would run it with an argument, that argument being the file where you would like to write the info.

>python mymemorygame.py savegamefile.txt 

You may also want to consider truncating the file, before writing to it depending on how you are saving the info (multiple files or one file)

I hope this helps, apologies if it doesn't I may have misunderstood what it is you are looking to do.

alternatively, it may be harder to write but easier to manage/implement, you could put the info in to a list that you store in a single file, rather than writing new .txt files all the time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...