我有一个包含这样的元组列表的文件:
(1,4)
(569,39)
(49,69)
。 。
我有这个CODE,但是同时读取所有行,我只想读取行,例如第1行,并且使用值x,y在函数中设置它们,然后返回第2行并取值x,y,再次执行,并在完成文件的长度后停止。
我可以在代码中更改什么以返回下一行?
import ast
def readfile():
filename = open('file.log')
result=[]
with open('file.log', 'r') as f:
lst = [ast.literal_eval(line) for line in f.readlines()]
for t in lst:
x, y = t
for t in [(x,y) for x in t[0:] for y in t[:1]]:
print x, y
value = (x, y)
result.append(value)
return result[1:-1]
print readfile()
答案 0 :(得分:1)
我的最终目标是:取第1行的值x,y并在其他函数中使用它们,当此函数完成时,返回第2行并取其他值再次执行,并在我的长度时停止我的档案已经完成。
听起来你想要一个迭代yield
来自文件的值的函数。示例实施:
import ast
def readfile():
with open('file.log', 'r') as f:
for line in f:
yield ast.literal_eval(line)
def do_something(a,b):
print "I am doing something with {} and {}".format(a,b)
for x,y in readfile():
do_something(x,y)
结果:
I am doing something with 1 and 4
I am doing something with 569 and 39
I am doing something with 49 and 69
答案 1 :(得分:0)
你很亲密,但似乎你感到困惑。如果我理解了这个问题,那就是:
for x, y in lst:
print x, y
答案 2 :(得分:0)
你的变量lst
是一个数组,所以如果你想要第一行,你可以返回lst [0]。
所以诀窍是存储lst
并写一个函数来返回lst [line-1]。像这样:
def get_at_line(lst, line):
# do some validation here
return lst[line-1]
x, y = get_at_line(lst, 1)
答案 3 :(得分:0)
只需替换
lst = [ast.literal_eval(line) for line in f.readlines()]
for t in lst:
与
for t in f.readlines():
答案 4 :(得分:0)
这是一个逐行缓冲文件的解决方案。缓冲可以节省RAM;如果文件很大,那就很有用。
我已将您的剧本改编为:
ast
:<强>输出强>
<强>代码强>
#######################
# define the function #
#######################
def readfile():
""" Reads a file consisting of a list of tuples (x, y) line-by-line. Prints x and y of the current line and the next line as reading ensues. """
file_in = open("./tuples.txt","r") # read the file in, I assume the script is run in the same directory as the tuples list
result = []
while True:
line = file_in.readline() # read the file line-by-line
go_back = file_in.tell() # "saves" the current line so we can step back
next_line = file_in.readline() # reads the line ahead
x,y = str(line).replace("(","").replace(")","").replace(" ","").rstrip().lstrip().split(",")
# Have we reached the end of the file?
try:
# No...
x_next, y_next = str(next_line).replace("(","").replace(")","").replace(" ","").rstrip().lstrip().split(",")
result.append([float(x),float(y)])
print "current line: "+str(x)+" "+str(y)+" ..next line: "+str(x_next)+" "+str(y_next)
except ValueError:
# Yes...
print "current line: "+str(x)+" "+str(y)+" ..next line: "+"NaN NaN"
break # break once we read a "next line" that does not exist, i.e. number of lines in file + 1
line = file_in.seek(go_back) # go back to previous line
return result
####################
# run the function #
####################
result = readfile()
print "\nresult: "+str(result)