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



我是初学者。我有一个简单的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:detestadmi.py", line 5, in <module>
    np.loadtxt("test2.txt")
  File "C:UsersMirceaAppDataRoamingPythonPython37site-packagesnumpylibnpyio.py", line 962, in loadtxt
    fh = np.lib._datasource.open(fname, 'rt', encoding=encoding)
  File "C:UsersMirceaAppDataRoamingPythonPython37site-packagesnumpylib_datasource.py", line 266, in open
    return ds.open(path, mode, encoding=encoding, newline=newline)
  File "C:UsersMirceaAppDataRoamingPythonPython37site-packagesnumpylib_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

最新更新