我是初学者。我有一个简单的 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.
请您参考如下方法:
可以改用Python读取文件吗?
path = '' # location of your file
openfile = open(path, 'r') # open file
openfile.read() # return all content of file
openfile.close() # close file
