按字母顺序对文本文件进行排序(Python) [英] Sorting a text file alphabetically (Python)

查看:192
本文介绍了按字母顺序对文本文件进行排序(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按字母顺序对文件"shopping.txt"进行排序

I would like to sort the file 'shopping.txt' in alphabetical order

shopping = open('shopping.txt')
line=shopping.readline()
while len(line)!=0:
    print(line, end ='')
    line=shopping.readline()
#for eachline in myFile:
#    print(eachline)
shopping.close()

推荐答案

只是显示一些不同的内容,而不是在python中这样做,您可以在Unix系统中的命令行中进行此操作:

Just to show something different instead of doing this in python, you can do this from a command line in Unix systems:

sort shopping.txt -o shopping.txt

,您的文件已排序.当然,如果您真的想要python:很多其他人提出的解决方案,可以读取文件并进行排序

and your file is sorted. Of course if you really want python for this: solution proposed by a lot of other people with reading file and sorting works fine

这篇关于按字母顺序对文本文件进行排序(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆