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

标签 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

最佳答案

使用.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])

关于python-2.7 - 如何使用python2.7从文本文件读取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46334722/

相关文章:

python-2.7 - 如何在python中使用内核计算图像的梯度

python - lambda 的字符串表示

C 文件创建不起作用

php - 将新值附加到 formData 对象时遇到问题

vb.net - 如何在vb.net中使用打开文件对话框指定路径?

python-2.7 - 我无法使用 python 安装 numpy 和 scipy

python - Python中如何在连续大写字母的首字母前添加空格?

file - MATLAB如何在文本文件中写入文件头

c++ - freopen() 的 Python 版本

python - Python 中的回溯错误问题