I am trying to read a file name stored as a string in a data file. No problem there. If I pass it to genfromtxt I get error "IOError: Z:\Python\Rb input.txt not found." if I put the file name into genfromtxt explicitly it works

this fails with error "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

but his works

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

the 2 print statements give

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

It appears to be to do with now the string is passed - any suggestions please

有帮助吗?

解决方案

rbfile has an End-Of-Line (EOL) character (e.g. \r\n) at the end. Strip it off:

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

By the way, to debug problems with strings, it is often more useful to print the repr of the string than the string itself:

print(repr(rbfile))

because the repr will show characters such as '\r\n' more clearly.


file.readline() does not strip EOF characters:

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous;

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top