我有以下代码:
# -*- coding: utf-8 -*-
import random
import os, glob
guessesTaken = 325
ha=0
print('Hello! What is your name?')
name = raw_input()
number = random.randint(1, 20)
print('Well, ' + name + ', I am thinking of a number between 1 and 20.')
while guessesTaken <10000 and ha<6:
print('Take a guess.') # There are four spaces in front of print.
guess = raw_input()
guess = int(guess)
guessesTaken = guessesTaken - 25
ha = ha+1
if guess < number:
print('Your guess is too low.') # There are eight spaces in front of print.
if guess > number:
print('Your guess is too high.')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
ha = str(ha)
print('Good job, ' + name + '! You guessed my number in ' + ha + ' guesses!')
xa=len(name)
f='f'
with open("f", "a") as myfile:
myfile.write('name')
myfile.write(': ')
myfile.write(name)
myfile.write(' ')
if len(name)==1:
myfile.write(25 *' ')
if len(name)==2:
myfile.write(24 *' ')
if len(name)==3:
myfile.write(23 *' ')
if len(name)==4:
myfile.write(22 *' ')
if len(name)==5:
myfile.write(21 *' ')
if len(name)==6:
myfile.write(20 *' ')
if len(name)==7:
myfile.write(19 *' ')
if len(name)==8:
myfile.write(18 *' ')
if len(name)==9:
myfile.write(17* ' ')
if len(name)==10:
myfile.write(16*' ')
if len(name)==11:
myfile.write(15*' ')
if len(name)==12:
myfile.write(14*' ')
if len(name)==13:
myfile.write(13*' ')
if len(name)==14:
myfile.write(12*' ')
if len(name)==15:
myfile.write(11*' ')
if len(name)==16:
myfile.write(10*' ')
if len(name)==17:
myfile.write(9*' ')
if len(name)==18:
myfile.write(8*' ')
if len(name)==19:
myfile.write(7*' ')
if len(name)==20:
myfile.write(6*' ')
if len(name)==21:
myfile.write(5*' ')
if len(name)==22:
myfile.write(4*' ')
myfile.write('score')
myfile.write(': ')
myfile.write(guessesTaken)
myfile.write('\n\n')
with open(f) as myfile:
print myfile.read()
我想看起来像:
1.姓名分数
2.姓名分数
3.姓名分数
。
。
。
。
。
。
我不知道如何在姓名前列举。
我想像记录一样对分数进行排序。
感谢您的帮助。
最佳答案
您可以尝试类似的操作,我在这里使用了附加模式('a'
)在文件底部附加了新行。我将格式留给您:
with open('data1.txt','a') as f,open('data1.txt') as f1:
lines=[x.strip() for x in f1] #read the lines
num=len(lines)+1
f.write("{0}.{1:22s}{2}\n".format((num),name,ha))
编辑:
我错过了排序部分,所以这是您的排序功能:
def sortfile(fil):
with open(fil,'r+') as f:
lines=[x.strip() for x in f]
lines.sort(key=lambda x:int(x.split()[-1])) #sort as per score
#print(lines)
f.truncate(0) #empty the file
f.seek(0) #move the cursor back to the start of the file
for i,x in enumerate(lines):
ind=x.index('.') #fetch the index of '.'
#print ("{0}.{1}\n".format(i+1,x[ind+1:]))
f.write("{0}.{1}\n".format(i+1,x[ind+1:]))
sortfile('data1.txt') #call the function whenever you want to sort the file as per scores
关于python - 我想使用python枚举文件中的文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12120065/