如何使用python2.7从文本文件中读取数据?

时间:2017-09-21 02:57:59

标签: python-2.7 file

任何人都可以尝试帮我检索Python中的数字,并将每个数字检索到数组: 我已经完成了以下代码,它完成了工作,但它将10作为两个数字读取:

with open("test.dat") as infile:
    for i, line in enumerate(infile):
        if i == 0:
            for x in range(0, len(line)):
                if(line[x] == ' ' or line[x] == "  "):
                    continue

                else:
                    print(x, " " , line[x], ", ")
                    initial_state.append(line[x])

---结果:

  (0, ' ', '1', ', ')
  (2, ' ', '2', ', ')
  (4, ' ', '3', ', ')
  (6, ' ', '4', ', ')
  (8, ' ', '5', ', ')
  (10, ' ', '6', ', ')
  (12, ' ', '7', ', ')
  (14, ' ', '8', ', ')
  (16, ' ', '9', ', ')
  (18, ' ', '1', ', ')
  (19, ' ', '0', ', ')
  (21, ' ', '1', ', ')
  (22, ' ', '1', ', ')
  (24, ' ', '1', ', ')
  (25, ' ', '2', ', ')
  (27, ' ', '1', ', ')
  (28, ' ', '3', ', ')
  (30, ' ', '1', ', ')
  (31, ' ', '4', ', ')
  (33, ' ', '1', ', ')
  (34, ' ', '5', ', ')
  (36, ' ', '0', ', ')
  (37, ' ', '\n', ', ')

索引包含空格,请参阅我试图添加到数组的数字行

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0

2 个答案:

答案 0 :(得分:1)

如果您确定每个数字由一个空格分隔,为什么不拆分该行并将每个元素打印为数组:

with open("test.dat") as infile:
    content = infile.read().split()
    for index, number in enumerate(content):
        print ((index*2, number))

您的确切输入和预期结果是什么?文件之间是否有多个空格?

答案 1 :(得分:1)

使用.split()通过循环分割所有字段,请参阅以下代码,它应该这样做

with open("test.dat") as infile:
       for i, line in enumerate(infile):
           if i == 0: # if first line
               field = [field.split(" ") for field in line.split(" ")]

               for x in range(0, len(field)):
                   initial_state_arr.append(field[x])