我的文件名中有1.000 1.050 1.100这样一直到2,我希望按顺序打开并进行操作,但是总是报错float object cannot be interpreted as an integer。我该怎么改第三行代码可以让它实现open
代码:
import os
for i in range(1,2,0.05):
with open(f'D:/test/test/a{"%.3f"i}', 'r') as f:
context = f.readlines()
target_line = 0
for l in context:
if l.find('test') != -1:
break
target_line += 1
with open('D:/test/out.txt', 'a') as file1:
print( context[target_line + 15], file=file1)
print( context[target_line + 16], file=file1)
range不支持小数吧,自己组合下就行
import os
lst=['a','b']#更多文件前缀
for c in lst:
for i in range(1000,2001,50):
file='D:/test/test/'+c+str(i)[0]+"."+str(i)[1:]
print(file)
#with open(file) as f:
#....其他代码逻辑
range()不支持小数,用while 循环即可
import os
li = ['a','b'] #文件前面字符串
for s in li:
i = 1
while i<=2.00001:
file = f'D:/test/test/{s}{i:.3f}'
print(file)
# with open(file, 'r') as f:
# context = f.readlines()
i+=0.05
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
for 后面放
a = a + str(i)
然后里面改成{a}就好了