如何转换可变模块搁置?

2024-09-28 05:28:19 发布

您现在位置:Python中文网/ 问答频道 /正文

请帮助转换变量“fileNameClean”,以便通过模块“shelve”打开文件

import shelve

fileName = 'C:/Python33/projects/DVD_LIST/p3_dvd_list_shelve_3d_class_edit_menubar/data.dir'
print('___', fileName)
str = fileName.split('/')[-1]
print('--', str)
fileNameClean = str.split('.')[0:-1]
print(fileNameClean)                #['data']

db = shelve.open(fileNameClean)     #open error

Tags: 模块文件importdataopenfilenamelistshelve
1条回答
网友
1楼 · 发布于 2024-09-28 05:28:19

使用^{}模块生成干净的路径:

import os.path

fileName = 'C:/Python33/projects/DVD_LIST/p3_dvd_list_shelve_3d_class_edit_menubar/data.dir'

fileNameClean = os.path.splitext(os.path.basename(fileName))[0]
db = shelve.open(fileNameClean)

您的代码还生成了一个减去扩展名的基名称,但是您通过使用切片(从索引0到但不包括最后一个元素)返回了一个列表。您可以使用fileNameClean[0],但是使用os.path模块可以确保在路径处理中也能捕获edgecase

你可能想确保你在这里也不使用相对路径。要打开与当前脚本或模块位于同一目录中的shelve文件,请使用__file__获取父目录的绝对路径:

here = os.path.dirname(os.path.abspath(__file__))
db = shelve.open(os.path.join(here, fileNameClean))

相关问题 更多 >

    热门问题