请帮助转换变量“fileNameClean”,以便您可以通过“搁置”模块打开文件
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
答案 0 :(得分:0)
使用os.path
模块生成一条干净的路径:
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
模块可确保在路径处理中捕获边缘项。
您可能希望确保此处也不使用相对路径。要在与当前脚本或模块相同的目录中打开shelve
文件,请使用__file__
获取父目录的绝对路径:
here = os.path.dirname(os.path.abspath(__file__))
db = shelve.open(os.path.join(here, fileNameClean))