Python 如何使用相对路径使用 Pandas 在 data_folder 中打开我的文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35384358/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:22:45  来源:igfitidea点击:

How to open my files in data_folder with pandas using relative path?

pythonpandasrelative-path

提问by Luis Ramon Ramirez Rodriguez

I'm working with pandas and need to read some csv files, the structure is something like this:

我正在使用熊猫,需要读取一些 csv 文件,结构是这样的:

folder/folder2/scripts_folder/script.py

folder/folder2/data_folder/data.csv

文件夹/folder2/scripts_folder/script.py

文件夹/folder2/data_folder/data.csv

How can I open the data.csvfile from the script in scripts_folder?

如何data.csv从脚本中打开文件scripts_folder

I've tried this:

我试过这个:

absolute_path = os.path.abspath(os.path.dirname('data.csv'))

pandas.read_csv(absolute_path + '/data.csv')

I get this error:

我收到此错误:

File folder/folder2/data_folder/data.csv does not exist

回答by SPKoder

Try

尝试

import pandas as pd
pd.read_csv("../data_folder/data.csv")

回答by CodeIsLife

# script.py
current_file = os.path.abspath(os.path.dirname(__file__)) #older/folder2/scripts_folder

#csv_filename
csv_filename = os.path.join(current_file, '../data_folder/data.csv')

回答by norman_h

You could use the __file__attribute:

您可以使用该__file__属性:

import os
import pandas as pd
df = pd.read_csv(os.path.join(os.path.dirname(__file__), "../data_folder/data.csv"))

回答by Kenan

Pandas will start looking from where your current python file is located. Therefore you can move from your current directory to where your data is located with '..' For example:

Pandas 将从您当前的 python 文件所在的位置开始查找。因此,您可以使用“..”从当前目录移动到数据所在的位置,例如:

pd.read_csv('../../../data_folder/data.csv')

Will go 3 levels up and then into a data_folder (assuming it's there) Or

将上升 3 个级别然后进入 data_folder(假设它在那里)或者

pd.read_csv('data_folder/data.csv')

assuming your data_folder is in the same directory as your .py file.

假设您的 data_folder 与您的 .py 文件位于同一目录中。

回答by MD Rijwan

For non-Windows users:

对于非 Windows 用户:

import pandas as pd
import os

os.chdir("../data_folder")
df = pd.read_csv("data.csv")

For Windows users:

对于 Windows 用户:

import pandas as pd

df = pd.read_csv(r"C:\data_folder\data.csv")

The prefix r in location above saves time when giving the location to the pandas Dataframe.

将位置提供给熊猫数据框时,上面位置中的前缀 r 可以节省时间。

回答by Rajesh Nair

import pandas as pd
df = pd.read_csv('C:/data_folder/data.csv')

回答by Dougz

I was also looking for the relative path version, this works OK. Note when run (Spyder 3.6) you will see (unicode error) 'unicodeescape' codec can't decode bytes at the closing triple quote. Remove the offending comment lines 14 and 15 and adjust the file names and location for your environment and check for indentation.

我也在寻找相对路径版本,这工作正常。请注意,当运行 (Spyder 3.6) 时,您将看到 (unicode error) 'unicodeescape' codec can't decode bytes at the Close Triple quote。删除有问题的注释行 14 和 15,并针对您的环境调整文件名和位置并检查缩进。

-- coding: utf-8 --

- - 编码:utf-8 --

""" Created on Fri Jan 24 12:12:40 2020

""" 创建于 2020 年 1 月 24 日星期五 12:12:40

Source: Read a .csv into pandas from F: drive on Windows 7

来源: 在 Windows 7 上从 F: 驱动器将 .csv 读入 Pandas

Demonstrates: Load a csv not in the CWD by specifying relative path - windows version

演示:通过指定相对路径加载不在 CWD 中的 csv - windows 版本

@author: Doug

@作者:道格

From CWD C:\Users\Doug\.spyder-py3\Data Camp\pandaswe will load file

从 CWDC:\Users\Doug\.spyder-py3\Data Camp\pandas我们将加载文件

C:/Users/Doug/.spyder-py3/Data Camp/Cleaning/g1803.csv

"""

"""

import csv

trainData2 = []

with open(r'../Cleaning/g1803.csv', 'r') as train2Csv:

  trainReader2 = csv.reader(train2Csv, delimiter=',', quotechar='"')

  for row in trainReader2:

      trainData2.append(row)

print(trainData2)

回答by Nikos Tavoularis

Keeping things tidy with f-strings:

使用f-strings保持整洁:

import os
import pandas as pd

data_files = '../data_folder/'
csv_name = 'data.csv'

pd.read_csv(f"{data_files}{csv_name}")

回答by hitesh dev

With python or pandas when you use read_csvor pd.read_csv, both of them look into current working directory, by default where the python process have started. So you need to use osmodule to chdir()and take it from there.

与Python或熊猫当您使用read_csv或者pd.read_csv,他们都考虑当前工作目录,默认情况下在Python进程已经开始。所以你需要使用osmodulechdir()并从那里获取它。

import pandas as pd 
import os
print(os.getcwd())
os.chdir("D:/01Coding/Python/data_sets/myowndata")
print(os.getcwd())
df = pd.read_csv('data.csv',nrows=10)
print(df.head())