【问题标题】:Genfromtxt file nameGenfromtxt 文件名
【发布时间】:2014-02-21 07:28:45
【问题描述】:

我正在尝试读取以字符串形式存储在数据文件中的文件名。那里没问题。如果我将它传递给 genfromtxt,我会收到错误“IOError: Z:\Python\Rb input.txt not found”。如果我将文件名明确地放入 genfromtxt 中,它就可以工作

此操作失败并出现错误“IOError: Z:\Python\Rb input.txt not found.”

import numpy
modat = open('z:\python\mot1 input.txt') # open file with names in
rbfile = modat.readline()                # read data file name
print rbfile                             # print the file name
rb = numpy.genfromtxt(rbfile, delimiter =',')
print rb

但他的作品

import numpy
modat = open('z:\python\mot1 input.txt') # open file with names in
rbfile = modat.readline()                # read data file name
print rbfile
rb = numpy.genfromtxt('z:\python\Rb input.txt', delimiter =',')
print rb

两个打印语句给出

%run "c:\users\ian\appdata\local\temp\tmpkiz1n0.py"
Z:\Python\Rb input.txt

[[  2.  10.]
 [  3.  11.]
 [  5.  13.]
 [ 10.  15.]
 [ 15.  16.]
 [ 20.  16.]
 [ 30.  22.]]

现在似乎与传递字符串有关 - 请提供任何建议

【问题讨论】:

  • 你试过rbfile.rstrip()吗?

标签: python file numpy names genfromtxt


【解决方案1】:

rbfile 末尾有一个行尾 (EOL) 字符(例如 \r\n)。脱掉它:

rb = numpy.genfromtxt(rbfile.strip(), delimiter =',')

顺便说一句,要调试字符串的问题,打印字符串的repr 通常比字符串本身更有用:

print(repr(rbfile))

因为repr会更清楚地显示'\r\n'等字符。


file.readline() 不会去除 EOF 字符:

f.readline() 从文件中读取一行;换行符 (\n) 留在字符串的末尾,仅在最后一个省略 如果文件不以换行符结尾,则为文件的行。这使得 返回值明确;

【讨论】:

  • 魔术!我已经搞砸了很多年,感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-26
  • 2015-07-15
  • 2016-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多