如何转换变量模块搁置?

时间:2014-01-31 11:50:45

标签: python python-3.x

请帮助转换变量“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

1 个答案:

答案 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))