python导入名称文件并按字母顺序排序

cml*_*ano 2 python file while-loop

我无法弄清楚为什么我的简单名称脚本不起作用.它似乎在while循环中出错.我可能错误地称它为,但我想我可能会在这里继续研究时尝试得到答案.

#!/usr/bin/python

#open the file
name_file = open('names.txt', 'r')

#read in lines
names = name_file.readlines()

#close file
name_file.close()

#loop to place names in array
index = 0
        while index < len(names):
             names[index] = names[index].rstrip('\n')
             index += 1
#sort
names.sort()

#print sorted names
print names
Run Code Online (Sandbox Code Playgroud)

Hyp*_*eus 6

也许这有效:

with open ('names.txt', 'r') as f:
    names = sorted (name.rstrip ('\n') for name in f)

print (names)
Run Code Online (Sandbox Code Playgroud)

with放下示波器后,将负责关闭文件.

  • 你不是白痴.你在学习,这是重要的部分.你无法从成功中吸取教训,你可以从错误中吸取教训.无论是来自你自己,还是来自他人. (4认同)