Python 按字母顺序对大型.txt文件进行排序
我对下面的Python脚本有点小问题 我正在尝试按字母顺序对列表进行排序(区分大小写,可能包括数字)。该列表由从输入文件读取的内容生成 输入文件相当大,大小约为219MB。但是,在我运行脚本之后,输出的.txt文件只有1570KB。有人能帮我确定为什么会这样吗Python 按字母顺序对大型.txt文件进行排序,python,Python,我对下面的Python脚本有点小问题 我正在尝试按字母顺序对列表进行排序(区分大小写,可能包括数字)。该列表由从输入文件读取的内容生成 输入文件相当大,大小约为219MB。但是,在我运行脚本之后,输出的.txt文件只有1570KB。有人能帮我确定为什么会这样吗 # The built-in function `open` opens a file and returns a file object. # Read mode opens a file for reading only. try:
# The built-in function `open` opens a file and returns a file object.
# Read mode opens a file for reading only.
try:
f = open("dict.txt", "r")
try:
# Read the entire contents of a file at once.
# string = f.read()
# OR read one line at a time.
#line = f.readline()
# OR read all the lines into a list.
lines = f.readlines()
lines.sort()
f.close()
f = open('output.txt', 'w')
f.writelines(lines) # Write a sequence of strings to a file
finally:
f.close()
except IOError:
pass
如果您尝试打印异常而不是
pass
?请正确输入。您的代码已损坏,您有两个try
,只有一个,只有一个。另外,当您运行控制台时,控制台中是否有任何输出?您为什么不执行排序dict.txt>output.txt
?@Daniel:我怀疑这是家庭作业。@Lawrence:他们有有效的代码<代码>尝试..最后
是完全合法的。这是一个相当古老的skool;有一段时间你可以使用try..finally
或try。现在已经改变了,但这并不意味着它无效。