excel_path = os.getcwd()
excel_fpath = 'exceldata//'
excel_final_path = os.path.join(excel_path, excel_fpath)
filename = excel_final_path + '系统导出-' + time.strftime("%Y-%m-%d",time.localtime()) + '.xls'
with open(filename, "wb") as code:
code.write(excelout.content)
print('表格下载完成')
按理说应该会存在于
D:/program/test/pythonfile/exceldata/系统导出.xls
但是变成
D:/exceldata/系统导出.xls
难道是我在程序一开始就执行一次上面的内容,然后在def里面又执行一次上面相同内容的问题吗?,也不应该呀。
我需要打开在python程序目录下子文件夹内的文件,为什么引用路径变成D盘根目录下去了呢?请问该怎么操作呢?
需要支持程序放在哪就在哪运行
D:/pythonfile/exceldata/系统导出.xls
E:/program/test/pythonfile/exceldata/系统导出.xls
a. os.path.abspath(file))
print(os.path.abspath(__file__))
b. os.path.realpath(file)
print(os.path.realpath(file))
a. os.path.split(os.path.abspath(file))[0]
print(os.path.split(os.path.abspath(file))[0])
b. os.path.dirname(os.path.abspath(file))
print(os.path.dirname(os.path.abspath(file)))
方法:
获取步骤2的结果,再使用一次 os.path.dirname()向上退一级;再利用 os.path.split()分割取第0个值即可
a. 得到当前目录: pwd = os.path.dirname(os.path.abspath(file))
b. 向上退一级目录: pwd1=os.path.dirname(pwd)
c. 分割最后一个\后和前面的目录:os.path.split(pwd1)[0]
os.getcwd() 方法用于返回当前工作目录,具体返回什么还跟ide的特性有关。比如vscode返回的是workspace路径,而不是具体执行py代码的目录路径。
可以配合os.chdir(path)。