有什么方法可以使用Python读取Excel文件而无需更改路径?

时间:2018-12-26 14:57:08

标签: python pandas

我有一个名为test的文件夹,我想在不同的计算机环境下用Python读取其test.xlsx。

#For Mac:
df = pd.read_excel('/Users/Steven/Desktop/test/test.xlsx')
#For Linux:
df = pd.read_excel('/Users/Users/Desktop/test/test.xlsx')
#For Windows:
df = pd.read_excel('C:/Users/Desktop/test/test.xlsx')

我想知道有什么方法可以在不更改文件路径的情况下以常规方式读取此文件。请分享任何有帮助的想法,谢谢。

df = pd.read_excel('../test/test.xlsx')

1 个答案:

答案 0 :(得分:0)

据我了解,您的想法是使用相对路径的概念读取文件。为此,我们可以使用os。假设您有一个包含/test/test.xlsx的父文件夹。在同一父文件夹中,我们可以插入我们的python程序(我们将其称为my_pretty_program.py):

import os
import pandas as pd

#gets your current directory
dirname = os.path.dirname(__file__)

#concatenates your current directory with your desired subdirectory
results = os.path.join(dirname, r'test\test.xlsx')

#reads the excel file in a dataframe
df = pd.read_excel(results, engine='python')

print(df)

这样,您就可以解决问题。记住结构如下:

Parent/
|-- my_pretty_program.py
|-- test/
|   |-- test.xlsx