【问题标题】:Why can't python/jupyer notebook find the text file? Where should it be saved?为什么 python/jupyter notebook 找不到文本文件?应该保存在哪里?
【发布时间】:2020-06-13 20:39:40
【问题描述】:

我正在尝试通过输入以下代码在 python 中将文本文件加载为数组:

from numpy import loadtxt
    values = loadtxt("values.txt", float)
    mean = sum(values)/len(values)
    print(mean)

但是当我运行程序时,我得到:

  OSError                                   Traceback (most recent call last)
<ipython-input-10-4b9a39f8b17f> in <module>
      1 from numpy import loadtxt
----> 2 values = loadtxt("values.txt", float)
      3 mean = sum(values)/len(values)
      4 print(mean)

~\Anaconda3\lib\site-packages\numpy\lib\npyio.py in loadtxt(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack, ndmin, encoding, max_rows)
    960             fname = os_fspath(fname)
    961         if _is_string_like(fname):
--> 962             fh = np.lib._datasource.open(fname, 'rt', encoding=encoding)
    963             fencoding = getattr(fh, 'encoding', 'latin1')
    964             fh = iter(fh)

~\Anaconda3\lib\site-packages\numpy\lib\_datasource.py in open(path, mode, destpath, encoding, newline)
    264 
    265     ds = DataSource(destpath)
--> 266     return ds.open(path, mode, encoding=encoding, newline=newline)
    267 
    268 

~\Anaconda3\lib\site-packages\numpy\lib\_datasource.py in open(self, path, mode, encoding, newline)
    622                                       encoding=encoding, newline=newline)
    623         else:
--> 624             raise IOError("%s not found." % path)
    625 
    626 

OSError: values.txt not found.

我将 values.txt 文件保存在我的文档文件夹中。我是否需要将它保存在某个特定的文件夹中以便 Python 可以找到它?

【问题讨论】:

  • 传递绝对路径而不仅仅是values.txt
  • 是的,它需要在你传递给函数的路径上values.txt 将被解释为您工作目录的相对路径,这显然不是您的文档文件夹。所以只需提供完整的路径。
  • 我添加了函数values=loadtxt("C:\\Users\\Willian\\Documents\\values.txt", float)的路径,但我仍然得到同样的错误。 @juanpa.arrivillaga

标签: python arrays text jupyter-notebook


【解决方案1】:

您可以使用绝对路径,也可以使用 loadtxt("values.txt", float) 但您的文件应该与您的脚本在同一个文件夹中 /jupyter。

【讨论】:

    猜你喜欢
    • 2023-03-11
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    相关资源
    最近更新 更多