【问题标题】:Jupyter Anaconda: load text file into pythonJupyter Anaconda:将文本文件加载到 python 中
【发布时间】:2017-01-25 07:12:59
【问题描述】:

我在 Mac 上运行 Anaconda Python 和 Jupyter。 输入以下代码后:

import numpy as np
import matplotlib.pyplot as plt
iris = np.genfromtxt("data/iris.txt",delimiter=None) 

我收到错误:IOError: data/iris.txt not found. 我已经尝试将 iris 文件放在 anaconda 文件夹中:Users/anaconda/lib/python2.7

【问题讨论】:

    标签: python anaconda jupyter-notebook jupyter


    【解决方案1】:

    在带有 Jupyter NoteBook 的 Anaconda Python 中,您必须使用 \\ 提供绝对路径,如下所示

    import pandas as pd
    df = pd.read_csv("D:\\Nu\\2SEMESTER\\Data Science\\Assignments\\Assignment-1 data\\file.txt")
    df     # with this command you can see your file
    

    【讨论】:

      【解决方案2】:

      您不应该将目标文件 data/iris.txt 放在 Anaconda 文件夹中。

      调用 Python 的地方就是放置文件的地方。

      # Bash
      $ cd Downloads/
      $ ls
      data/
      
      $ cd data/
      $ ls
      iris.txt
      
      $ cd ..
      $ python script.py
      

      当 Python “搜索”文件时,它会搜索任一文件

      • 从调用它的目录开始(如果您使用相对路径 - 不以 / 字符开头的路径
      • Root(如果您使用绝对路径 - 以 / 开头的路径,即 Root)

      如果您希望脚本能够从任何目录运行,请在代码中使用绝对路径

      import os
      
      base_path = "/path/to/directory/holding/file/"
      filename = "iris.txt"
      path_to_file = os.path.join(base_path, filename)
      fd = open(path_to_file , 'r')
      

      最好将此路径指定为变量,以便将来轻松更改。我已经包含了额外的(在这种情况下是冗余的)代码,让您了解可以使用的可能功能

      【讨论】:

      • 但错误提示:Traceback (last last call last): File "", line 1, in File "/Users/ashwinc/anaconda/lib/python2.7/ site-packages/numpy/lib/npyio.py”,第 1451 行,在 genfromtxt 这不是说在 anaconda 文件夹中搜索吗?
      • 这就是 Traceback。它正在经历“失败”的程序的每一步,指定哪个确切的函数调用引发了错误。在这种情况下npyio.py。函数 npyio.py 引发了错误 IOError: data/iris.txt not found. 。或者换句话说,Traceback 只是告诉你一些函数试图告诉你一些错误。
      • 好的。所以我使用了你的导入操作系统代码 sn-p。在 base_path 中,我将目录放入桌面中包含虹膜数据的文件夹中。然后我在你写的时候复制了你的其余代码。然后我重新运行 import numpy as np import matplotlib.pyplot as plt iris = np.genfromtxt("data/iris.txt",delimiter=None)。我仍然得到同样的错误
      • 不,上面的代码是如何使用绝对路径的示例。简单地说,函数调用np.genfromtext(...)中第一个参数指定的路径如果是相对路径,则必须指向调用Python的位置文件。
      • op 指的是 jupyter notebook 吗?
      【解决方案3】:
      from pathlib import Path
      
      #file = Path.joinpath('Resources', 'test.txt')
      file = Path.cwd() / 'Resources/test.txt'
      #file.read_text()
      
          # Open the file in "read" mode ('r') 
      with open(file, 'r') as text:
          textfile = text.read()
          print(textfile)
      

      导入模块路径库。 更多信息可以在 https://realpython.com/python-pathlib/

      【讨论】:

        猜你喜欢
        • 2021-11-15
        • 2021-01-22
        • 2015-05-19
        • 1970-01-01
        • 2018-04-26
        • 2014-02-12
        • 2019-01-04
        • 1970-01-01
        • 2011-08-18
        相关资源
        最近更新 更多