【问题标题】:Not able to read data from the input file无法从输入文件中读取数据
【发布时间】:2017-01-22 18:50:25
【问题描述】:

我正在尝试读取以下输入文件,这是我的代码和输入文件 click here 的 pastebin 链接:

 1       42.5340919495   4.22926330566
 2       41.3636322021   2.87980079651
 3       38.7423553467   3.40052604675
 4       36.631401062    2.33657073975
 5       35.0620422363   3.57421207428

这就是我生成输入文件的方式:

with open('position/output.dat','a') as output:

    for i in range(0, len(position_mean)):

        output.write('{}\t{}\t{}'.format(i+1, position_mean[i] , position_std[i]) + "\n" )

output.close()

这就是我读取输入文件的方式:

with open("position/output.dat", 'r') as f:
    x = []
    y = []
    z = []
    for line in f:
        if not line.strip() or line.startswith('@') or line.startswith('#'):
            continue
        row = line.split("\t")
        x.append(float(row[0]))
        y.append(float(row[1]))
        z.append(float(row[2]))

x = np.asarray(x)
y = np.asarray(y)
z = np.asarray(z)

但是当我打印 x、y、z 时,没有显示任何输出。这里可能出现什么错误?

【问题讨论】:

  • 请显示实际的缩进!
  • 使用正确的缩进,这确实打印输出xyz(在添加适当的打印语句并将line.split("\t")更改为@之后987654329@)。我投票决定将其作为一个无法重现的问题来解决。

标签: python numpy file-handling


【解决方案1】:

您的缩进看起来可能是导致问题的原因。

with open("stack_test.txt", 'r') as f:
    x = []
    y = []
    z = []
    for line in f:
       if not line.strip() or line.startswith('@') or line.startswith('#'):
          continue
       row = line.split("\t")
       x.append(float(row[0]))
       y.append(float(row[1]))
       z.append(float(row[2]))

    x = np.asarray(x)
    y = np.asarray(y)
    z = np.asarray(z)

【讨论】:

  • 我 83% 确定这是 OP 实际运行的代码,他的代码中的缩进问题只是他帖子中的格式错误。
  • @Tagc 抱歉,我的网络中断了。无法回复。你说对了 83%,但这是一个帖子格式问题。
猜你喜欢
  • 1970-01-01
  • 2019-04-10
  • 2017-02-05
  • 1970-01-01
  • 2013-10-18
  • 1970-01-01
  • 2019-08-11
  • 1970-01-01
相关资源
最近更新 更多