简体   繁体   English

如何使用 pandas 在 python 中打开 excel 文件?

[英]how to open excel file in python using pandas?

How do you open an xls or csv file in python without having to connect the whole path?如何在不连接整个路径的情况下打开 python 中的 xls 或 csv 文件?

ex: instead of using c:/user/...filename how do you connect it with just filename?例如:而不是使用 c:/user/...filename 你如何将它与文件名连接? is it possible using pandas?是否可以使用 pandas? This is in order to transfer the code from on console to another and the code being able to open with ease.这是为了将代码从控制台传输到另一个控制台,并且代码能够轻松打开。 From my understanding, if I use the path and send the code to another computer the excel page won't open there.据我了解,如果我使用该路径并将代码发送到另一台计算机,则 excel 页面将不会在那里打开。 btw the code will be sent with the original excel sheet顺便说一句,代码将与原始 excel 表一起发送

In this case, I believe you would have to set your working directory to the absolute path of your.py file.在这种情况下,我相信您必须将工作目录设置为 your.py 文件的绝对路径。

Note, for the code below, your.csv file should be in the same directory as your.py file.请注意,对于下面的代码,您的.csv 文件应与 your.py 文件位于同一目录中。

import os.path
import pandas as pd

base_dir = os.path.dirname(os.path.abspath(__file__)) # set directory to location of .py file
os.chdir(base_dir) # change directory 
csv_file = pd.read_csv('file.csv',sep=',') # read .csv

Similar to solution of @Ira H., but instead of changing working directory you can generate full path:类似于@Ira H. 的解决方案,但您可以生成完整路径,而不是更改工作目录:

import os.path
import pandas as pd

base_dir = os.path.dirname(
    os.path.abspath(__file__)
)  # set directory to location of .py file
csv_file = pd.read_csv(f"{base_dir}\\full_paths.csv", sep=",")  # read .csv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM