1

我正在尝试读取作为字符串存储在数据文件中的文件名。那里没问题。如果我将它传递给 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

2个打印语句给出

%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.]]

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

4

1 回答 1

3

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

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

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

print(repr(rbfile))

'\r\n'因为 repr 会更清楚地显示诸如此类的字符。


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

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

于 2014-01-29T13:11:59.023 回答