简体   繁体   English

用python abspath获取的路径打开Excel工作簿

[英]open Excel workbook with path obtained by python abspath

I try to write a python script to open an Excel file and read the value of the first cell of a sheet. 我尝试编写一个python脚本来打开Excel文件并读取工作表的第一个单元格的值。 This works when I write the path name myself, but I want to make it dynamic. 当我自己编写路径名时,此方法有效,但我想使其动态化。 So whenever I change the location of the Excel file together with the python file I automatically have the right path name. 因此,每当我更改Excel文件和python文件的位置时,我都会自动获得正确的路径名。

This is my script: 这是我的脚本:

import xlrd
import time
from os.path import dirname, abspath

loc=dirname(dirname(abspath(__file__)))
loc=loc+"\lijst.xlsx"

print("loc ->",loc)
wb=xlrd.open_workbook(loc)
sheet1=wb.sheet_by_index(0)
naam=sheet1.cell_value(0,0)
print("naam: ",naam)

when I run this, I get an error message: "FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Tracy\\Desktop\\lijst.xlsx". 运行此命令时,出现错误消息:“ FileNotFoundError:[Errno 2]没有此类文件或目录:'C:\\ Users \\ Tracy \\ Desktop \\ lijst.xlsx”。

Why is this ? 为什么是这样 ?

It is better to os.path.join for joining paths 最好使用os.path.join来连接路径

changing 改变中

loc=loc+"\lijst.xlsx"

to

loc = os.path.join(loc, 'lijst.xlsx')

should work. 应该管用。

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

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