Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用python打印.txt文件中每行的第一个单词_Python_Python 3.x_List_Sorting_File Handling - Fatal编程技术网

用python打印.txt文件中每行的第一个单词

用python打印.txt文件中每行的第一个单词,python,python-3.x,list,sorting,file-handling,Python,Python 3.x,List,Sorting,File Handling,我正在开发一个程序,该程序从.txt文件中提取学生姓名和成绩,并生成结果。文本文件具有以下类型的表单: Darnell 96 54 94 98 76 Brody 50 65 65 65 70 Anna 76 54 76 76 76 Conor 95 95 95 95 我希望输出的第一行显示学生的姓名,如下所示: Name of students in class: Anna Brody Conor Darnell 我现在的代码是 f = open(argv[1]) wh

我正在开发一个程序,该程序从.txt文件中提取学生姓名和成绩,并生成结果。文本文件具有以下类型的表单:

Darnell 96 54 94 98 76

Brody 50 65 65 65 70 

Anna 76 54 76 76 76

Conor 95 95 95 95 

我希望输出的第一行显示学生的姓名,如下所示:

Name of students in class:
Anna Brody Conor Darnell
我现在的代码是

   f = open(argv[1])
   while True:
      line = f.readline().strip()
      if line:
         print(line)
我知道我需要使用
sorted()
函数。然而,当我试图实现它时,我只是把代码弄得一团糟

我知道也有类似的问题。然而,作为python的新手,我对某些方面感到有些不知所措。 任何一点信息都有帮助。谢谢

你可以试试这个

我建议对open(…)使用
,因为您不需要显式地使用
close()

正如@Jan所建议的,您可以使用列表理解来编写所有这些内容

我根据这个链接写了下面的内容

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

但我建议使用下面的答案

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

如果线之间有线间距,请使用此选项

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

“我希望输出的第一行显示学生的姓名,如:”-->first line或first word??为什么使用while True?您可能需要使用listcomp。
with open('score.txt','r') as f:
        names=[]
        for line in f:
                if line.strip():
                        names.append(line.split()[0])
print(*sorted(names),sep=' ')