.readlines()会执行以下操作:逐行读取文件。在您的示例中,只有一行,因此长度为1。
在这一行中,您需要分割逗号:
with open(file1.txt,'r') as myfile:
for line in myfile:
print sorted(map(int, line.split(',')))
或者,如果您有多行包含大量数字:
data = []
with open(file1.txt,'r') as myfile:
for line in myfile:
data.extend(map(int, line.split(',')))
print sorted(data)
在这里,我使用withwith关键字来打开文件,可以逐行对其进行迭代。然后,在每一行上使用字符串的split方法,该方法将返回字符串列表。然后,我通过将int类型转换函数应用于列表中的每个项目,使用map将这些字符串转换为整数。然后可以对该列表进行排序。确保查看Python文档上的字符串方法页面。
没有输入文件的测试:
numbers = "10,45,69,85,21,7,32,11,71,20,30"
data = []
data.extend(map(int, numbers.split(',')))
print sorted(data)
版画
[7, 10, 11, 20, 21, 30, 32, 45, 69, 71, 85]