无法读取python中的简单txt文件

时间:2019-07-18 14:58:40

标签: python

我是初学者。我有一个简单的txt文件,我需要阅读(使用numpy)。我将程序与.txt文件放在同一目录中。

我检查了cwd,它是正确的。另外,我编写了一个文本文件,以查看python是否要打开该文件-该文件打开就好了。

import os
import numpy as np

np.loadtxt("test2.txt")

上面的代码给我错误。

下面的代码可以正常工作。

import os
import numpy as np

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

我得到的错误是:

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.

1 个答案:

答案 0 :(得分:1)

您可以改为使用Python读取文件吗?

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