简体   繁体   中英

Print out first word in each row from .txt file in python

I'm working on a program that takes student names and grades from a .txt file and produces results. The text file has this type of form:

Darnell 96 54 94 98 76

Brody 50 65 65 65 70 

Anna 76 54 76 76 76

Conor 95 95 95 95 

I want the first line of the output to show the names of students, like so:

Name of students in class:
Anna Brody Conor Darnell

My current code is

   f = open(argv[1])
   while True:
      line = f.readline().strip()
      if line:
         print(line)

I know I need to used the sorted() function. However, when I try to do implement it I just make a mess of the code.

I know theres similar questions out there. However, being new to python some are way over my head. Any little bit of information helps. Thanks!

You can try this.

I suggest using with open(...) because you don't need to explicitly use close() .

with open(argv[-1]) as f:
    names=[]
    for line in f:
        names.append(line.split()[0])

print(*sorted(names),sep=' ')
#Anna Brody Conor Darnell

As suggest by @Jan you can write all of that using a list comprehension.

Does using list comprehension to read a file automagically call close() I wrote the below in accordance with this link.

print(*sorted([line.split()[0] for line in open('score.txt','r') if line.split()]),sep=' ') #This single code does what you wanted
#Anna Brody Conor Darnell

But I suggest using this answer below.

with open(argv[-1],'r') as f:
    print(*sorted([line.split()[0] for line in f],sep=' ')

Use this if you have a line gap between lines.

with open('score.txt','r') as f:
        names=[]
        for line in f:
                if line.strip():
                        names.append(line.split()[0])
print(*sorted(names),sep=' ')

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