嗨我希望我的文件一行一行地读取坐标:
(124,125)
(160,230)
我需要逐行读取(x,y),并获取值并运行我的模型的细化。我想自动完成,而不是手动操作。
我有这个代码:
#! /usr/bin/env python
import sys
import os
old_stdout = sys.stdout
log_file = open ('listprueba.log', "w")
sys.stdout = log_file
with open('list.log') as f:
for line in f:
a,b = map(int,line.translate(None,"()[],").split())
("x = {}\ny = {}".format(a,b))
print (a, b)
sys.stdout = old_stdout
log_file.close()
def readfile(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 item in range(len(data)):
parentesisi = data[item].find('(')
coma = data[item].find(',')
parentesisd = data[item].find(')')
data[item] = (int(data[item][parentesisi+1:coma]), int(data[item][coma+1:parentesisd]))
return data
def main():
for i in readfile('coordinates.log'):
x=i[0]
y=i[1]
if __name__ == '__main__':
main()
这部分没关系,它是程序的一部分
log.verbose()
env = environ()
class MyLoop(loopmodel):
# This routine picks the coordinates to be refined by
def select_loop_atoms(self):
# coordinate insertion
return selection(self.residue_range(x, y)
我有这个错误:
ValueError: invalid literal for int() with base 10: ''
我只是想读取具有坐标(124,125)的第一行并且在x,y中存储值,并运行refinament。然后,返回具有坐标(160,230)的第2行,并相对于我的文件的长度执行相同的操作。
如何改进此代码?
非常感谢
答案 0 :(得分:0)
看起来你正试图在剥离之前转换一条线,所以你要用str.split
在某处拆分一个空字符串。试试这个:无论如何它看起来更漂亮。
import ast
with open('path/to/file.txt') as inf:
for line in inf:
line = line.strip() # strip the line first
if not line:
continue # skip blank lines
x,y = ast.literal_eval(line)
# the format (x, y) is a literal tuple. Treat it that way
如果你想要一个所有元组的列表:
with open('path/to/file.txt') as inf:
result = [ast.literal_eval(line) for line in inf if line.strip()]