![](/img/trans.png)
[英]Sorting text file into lists of every new line, finding the biggest value and printing the number of the line in which it is
[英]Printing to a new line after sorting a text file
對於我的任務,我必須能夠對已排序的文本文件中的數據進行打印。 我已經能夠對其進行排序,但是即使在記事本中它們位於單獨的行中,它也不會將其打印到新行中。
我的記事本文檔具有以下內容: http : //i.stack.imgur.com/Xn0pT.png
我已經設置的代碼是:
file = open(class_name , 'a') #opens the file in 'append' mode so you don't delete all the information
name = (name)
file.write(str(name + " : " )) #writes the information to the file
file.write(str(score))
file.write('\n')
file.close() #safely closes the file to save the information
viewscore = input("Do you wish to view previous results for your class").lower()
if viewscore == "yes".lower():
f = open(class_name , "r")
lines = [line for line in f if line.strip()]
f.close()
lines.sort()
print (lines)
我擁有的變量是:
class_name = class_name + ".txt"
name = input().title()
然后,當運行輸出時,我得到的是:
['Dan : 0\n', 'Jana : 0\n', 'Kyle : 0\n']
請告訴我是否必須添加任何內容。
這是適合我的工作版本:
class_name = 'data.txt'
name = 'Jim'
score = 100
file = open(class_name , 'a') #opens the file in 'append' mode so you don't delete all the information
line_data = name + " : " + str(score) + "\n" # data to write
file.write(line_data)
file.close() #safely closes the file to save the information
viewscore = raw_input("Do you wish to view previous results for your class?").lower()
if viewscore == "yes".lower():
f = open(class_name , "r")
lines = [line for line in f if line.strip()]
f.close()
lines.sort()
for line in lines:
print line
else: # add else case to debug
print 'no for', viewscore
首先,可以將要編寫的行放入變量中,然后再編寫。
其次,如果您使用Python2.x,請使用raw_input()
作為輸入字符串。
第三,如果您具有if
,則最好編寫一個else
以便於調試代碼。
您應該嘗試此代碼。 你為什么要分別寫三件事? 它可能是將\\ n寫為字符串,而不是將其放在換行符中。
f.write(name+' : '+str(score)+'\n')
您要打印的是稱為lines
的列表,而查看輸出的方式就是顯示類型列表的方式。 您要做的是將列表的內容打印為一個字符串。 為此,您可以按以下方式join
內容:
In [1]: lines = ['Dan : 0\n', 'Jana : 0\n', 'Kyle : 0\n']
In [2]: print "".join(lines)
Dan : 0
Jana : 0
Kyle : 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.