我有一个包含这样的值的文件:
(1, 3)
(4, 5)
(15, 39)
并使用它像值(x,y)。
我首先想将整数1存储到变量'x'中,然后将整数3存储到变量'y'中,然后我想在方法中使用它们。然后我想将第二行4存储到变量'x'中,将5存储到变量'y'中。所以基本上只重复使用两个'x'和'y',暂时在方法中使用它们并将下一行输入存储到这些变量中,依此类推。示例:
x = 1
y = 3
z = x + y
print z = 4
return x, y #Here return to line 2 (4, 5)
print z = 9
依此类推....当文件完成时停止。
答案 0 :(得分:0)
你走了:
#!/usr/bin/env python2.7
def read_file(filename):
# opens file, reads contents, and splits it by newline
with open(filename, 'r') as f:
data = f.read().split('\n')
# iterates through data and converts each string to a tuple
for i in range(len(data)):
lparen = data[i].find('(')
comma = data[i].find(',')
rparen = data[i].find(')')
data[i] = (int(data[i][lparen+1:comma]), int(data[i][comma+1:rparen]))
return data
def main():
for i in read_file('ParsingCoordsInput.txt'):
print i[0] + i[1]
if __name__ == '__main__':
main()
几点说明:
修改强>
这是Python 3.x的代码。唯一的区别是在print周围添加括号(因为它在3.0中成为一个函数)。享受!
#!/usr/bin/env python3
def read_file(filename):
# opens file, reads contents, and splits it by newline
with open(filename, 'r') as f:
data = f.read().split('\n')
# iterates through data and converts each string to a tuple
for i in range(len(data)):
lparen = data[i].find('(')
comma = data[i].find(',')
rparen = data[i].find(')')
data[i] = (int(data[i][lparen+1:comma]), int(data[i][comma+1:rparen]))
return data
def main():
for i in read_file('ParsingCoordsInput.txt'):
print(i[0] + i[1])
if __name__ == '__main__':
main()