简体   繁体   中英

Printing to a new line after sorting a text file

For my task I have to be able to print the data that is in text file after it has been sorted. I have been able to sort it but it dosen't print it to a new line even though in notepad they are on seperate lines.

My Notepad Documents has this: http://i.stack.imgur.com/Xn0pT.png

The code I already have set up is:

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)

The Variables I have are:

class_name = class_name + ".txt"  
name = input().title()

Then when run the output I get is:

['Dan : 0\n', 'Jana : 0\n', 'Kyle : 0\n']

Please tell me if I have to add anything.

Here is a work version for me:

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

First, you can put the line you want to write in a variable, and then write it.

Second, if you use Python2.x, use raw_input() for input string.

Third, if you have a if , better to write an else for easy to debug the code.

You should try this code. Why are you writing 3 things separately? It is probably writing \\n as a string, not putting things in new line.

f.write(name+' : '+str(score)+'\n')

What you are printing is the list you called lines and the way you see the output is the way the type list is displayed. What you want to do is print the content of the list as one string. For that you can join the content as follow:

In [1]: lines = ['Dan : 0\n', 'Jana : 0\n', 'Kyle : 0\n']
In [2]: print "".join(lines)
Dan : 0
Jana : 0
Kyle : 0

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