Mircea Greveanu
Mircea Greveanu

Reputation: 21

cannot read simple txt file in python

I am a beginner. I have a simple txt file which I need to read (using numpy). I have the program in the same directory as the .txt file.

I have checked the cwd and it's the right one. Also, I've written a text file in order to see if python wants to open that one - that file opens just fine.

import os
import numpy as np

np.loadtxt("test2.txt")

The code above gives me the error.

The code below works just fine.

import os
import numpy as np

x = np.array([1, 2, 3])
np.savetxt("test.txt", x)
y = np.loadtxt("test.txt")
print(y)

The error I get is:

Traceback (most recent call last):
  File "D:\detest\admi.py", line 5, in <module>
    np.loadtxt("test2.txt")
  File "C:\Users\Mircea\AppData\Roaming\Python\Python37\site-packages\numpy\lib\npyio.py", line 962, in loadtxt
    fh = np.lib._datasource.open(fname, 'rt', encoding=encoding)
  File "C:\Users\Mircea\AppData\Roaming\Python\Python37\site-packages\numpy\lib\_datasource.py", line 266, in open
    return ds.open(path, mode, encoding=encoding, newline=newline)
  File "C:\Users\Mircea\AppData\Roaming\Python\Python37\site-packages\numpy\lib\_datasource.py", line 624, in open
    raise IOError("%s not found." % path)
OSError: test2.txt not found.

Upvotes: 2

Views: 673

Answers (1)

Barb
Barb

Reputation: 437

Can you use the Python read file instead?

path = ''                  # location of your file
openfile = open(path, 'r') # open file
openfile.read()            # return all content of file
openfile.close()           # close file

Upvotes: 1

Related Questions