无法在Python中从文件读取int

时间:2014-02-16 20:06:58

标签: python file

如果一行中有多个整数,如何将行转换为整数。 (在完成时,该行可能是“2 4”并且finish = int(line)导致和错误。

另外,如何在底部的for循环中访问特定的过渡元素。我知道我可以打印列表,但我需要比较具体的元素?

with open(r'C:\Users\Andrew\Documents\College\Theory of Computation\dfa19btest.txt', 'r') as f:
   for i, line in enumerate(f):
   if i == 0:
       language = line
       print("Language =", language)
   if i == 1:
       numstates = int(line)
       print ("Number of states =", numstates)
   if i == 2:
       start = int(line)
       print ("Start =", start)
   #if i == 3:
       #finish = int(line)
       #print ("Finish =", finish)
   if i >= 4:
       transitions.append(line)
       print ("Transitions = ", transitions[i -4])

for x in range(numstates-1, -1, -1):
    print(transitions[x])
    # string is in 4 a 2 b 3 format
    # if [0] == [3] then answer insert [2]* into answer array
    # if [2] and [4] are followed by same number insert [2]|[4]

3 个答案:

答案 0 :(得分:0)

要将字符串解析为整数,请使用:int

例如:

str_var = '123'
int_var = int(str_var) # int_var now have the interger value 123

答案 1 :(得分:0)

如果您的任何输入无效,您需要决定应该发生什么,即非整数。以下是Python2的简化示例。请注意try / except子句。

with open(r'C:\Users\Andrew\Documents\College\Theory of Computation\dfa19btest.txt', 'r') as f:
   for i, line in enumerate(f):
       if i == 0:
           language = line
           print("Language =", language)
       try:
           if i == 1:
               numstates = int(line)
               transitions = np.array(numstates)
               print ("Number of states =", numstates)
           if i == 2:
               start = int(line)
               print ("Start =", start)
           if i == 3:
               finish = int(line)
               print ("Finish =", finish)
       except ValueError:
           print "Invalid int (%s) on line: %d" % (line, i)  # use print() for Python3
           break

答案 2 :(得分:0)

对于一行上的多个整数,str.split()函数将非常有用:http://docs.python.org/2/library/stdtypes.html#str.split

a = "1 2 3 4"
print a.split()   -> ["1", "2", "3", "4"]

你的问题的结尾还不清楚 - 你想用特定的元素做什么?