Jupyter Anaconda:将文本文件加载到 python 中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41845518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jupyter Anaconda: load text file into python
提问by bot
I have Anaconda Python and Jupyter running on Mac. After typing the following code:
我在 Mac 上运行 Anaconda Python 和 Jupyter。键入以下代码后:
import numpy as np
import matplotlib.pyplot as plt
iris = np.genfromtxt("data/iris.txt",delimiter=None)
I get the error: IOError: data/iris.txt not found.
I have tried putting the iris file in the anaconda folder: Users/anaconda/lib/python2.7
我收到错误:IOError: data/iris.txt not found.
我尝试将 iris 文件放在 anaconda 文件夹中:Users/anaconda/lib/python2.7
回答by Muhammad Kashif Arif
in Anaconda Python with Jupyter NoteBook you have to give the absolute path with \\ just like given below
在带有 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
回答by Jamie Phan
You should not be putting the target file data/iris.txt
in the Anaconda folder.
您不应该将目标文件data/iris.txt
放在 Anaconda 文件夹中。
Where you invoke Python, is where you should put the file.
调用 Python 的位置就是应该放置文件的位置。
# Bash
$ cd Downloads/
$ ls
data/
$ cd data/
$ ls
iris.txt
$ cd ..
$ python script.py
When Python 'searches' for files it will either search either
当 Python“搜索”文件时,它要么搜索
- From the directory it was called from (if you use a relative path - one that doesn't start with a
/
character - Root (if you use absolute paths - one that starts with
/
i.e. Root)
- 从它被调用的目录中(如果您使用相对路径 - 不以
/
字符开头的路径 - Root(如果您使用绝对路径 - 以
/
Root开头的路径)
If you want your script to be able to run from any directory use absolute paths in your code
如果您希望脚本能够从任何目录运行,请在代码中使用绝对路径
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')
It may be better practice to specify this path as a variable so that it can be easily changed in the future. I've included additional (redundant in this case) code to give you an idea of possible functions you can use
将此路径指定为变量可能是更好的做法,以便将来可以轻松更改。我已经包含了额外的(在这种情况下是冗余的)代码,让您了解可以使用的可能功能