返回信息流目标是完成对txt中的内容排序,txt中内容如下:
D03M1 9.1 The Shawshank Redemption (1994) 523,454
D03M10 8.8 Star Wars: Episode V - The Empire Strikes Back (1980) 279,549
D03M2 9.1 The Godfather (1972) 413,724
D03M3 9.0 The Godfather: Part II (1974) 247,199
D03M4 9.0 Inception (2010) 198,670
D03M5 8.9 Il buono, il brutto, il cattivo. (1966) 161,898
D03M6 8.9 Pulp Fiction (1994) 420,655
D03M7 8.9 Schindler's List (1993) 278,237
D03M8 8.8 12 Angry Men (1957) 120,338
D03M9 8.8 One Flew Over the Cuckoo's Nest (1975) 216,124
我自己写了个程序,但是第二次readlines()进不去。程序如下:
f1=open(r'e:\before_test.txt','r')
f2=open(r'e:\after_test.txt','w')
for i in range(1,251):
print 'i=',i
for line in f1:
print 'exe readlines'
print 'line=',line
s1=line.split()
s2=s1[0]
n=s2[4:]
n=int(n)
print 'n=',n
if i==n:
f2.write(line+'\n')
f1.close()
f2.close()
问题是,除了i=1的时候,i=2以后为什么不执行 for line in f1:那句。
另外,大家都是怎么处理这种类型的排序问题呢?
这是一条镜像帖。来源:北邮人论坛 / python / #3237同步于 2014/9/1
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Python机器人发帖
对同时带有字母和数字的字符串排序
hongdouzhou
2014/9/1镜像同步3 回复
订阅后,新回复会通过你的通知中心匿名送达。
3 条回复
for line in f1是文件迭代,就像一个指针指向了文件结尾,当你第二次for i in range(255)时候指针已经指向文件尾了,所以第二次读取不到
针对你的文件内容,我有个取巧的方法。将数字看做列表下标,数字对应的字符串为相应的值
f1 = open(r'i:\before_test.txt', 'r')
f2 = open(r'i:\after_test.txt', 'w')
d1=[]
count = 0
for i in range(20):
d1.append(i)
for i in f1:
print 'line = ', i,
s1 = i.split()
s2 = s1[0]
print s2
n = s2[4:]
d1[int(n)]=i
count = count+1
for i in range(count):
f2.write(d1[int(i+1)])
print d1
f1.close()
f2.close()