在python 2.7中获取文件路径

时间:2016-07-28 06:10:39

标签: python-2.7

我在获取文件路径时遇到了一些麻烦,因此我可以从指定的(文本)文件中打开并执行我的数据。下面是我到目前为止编写的代码:

def pickfile():
    options={}
    options['defaultextension'] = '.txt'
    options['filetypes'] = [('all files','.*'), ('text files', '.*txt')]
    options['initialfile'] = 'sample.txt'
    options['initialdir'] = 'C:\Users\profcs\Desktop'

    filename=open(tkFileDialog.askopenfilename(**options))
    if filename:
        print(filename)
        return 
    with open(filename, 'rb') as f:
        reader = csv.reader(f)
        try:
            for row in reader:
                print row
        except csv.Error as e:
            sys.exit('file %s, line %d: %s' % (filename, reader.line_num,e))

but1 = Button(widget1, text='Pick Your File', command=pickfile)
but1.pack(side=BOTTOM, padx=10, pady=1, anchor=SE)
but1.config(relief=RAISED, bd=2)

当我显示文件名时,我现在以这种形式获得路径:

================ RESTART: C:\Users\profcs\Desktop\BD TEST.py ================
<open file u'C:/Users/profcs/Desktop/sample.txt', mode 'r' at 0x01EFF128>

如何过滤此路径并仅获取'C:/Users/profcs/Desktop/sample.txt'以便我可以打开文件?

提前致谢。

1 个答案:

答案 0 :(得分:0)

filename.name为您提供filename对象的路径。

我希望这会有所帮助:

filename = open(tkFileDialog.askopenfilename(**options))
print (filename.name)
'C:/Users/profcs/Desktop/sample.txt'

在您的情况下,filename是一个表示打开文件的对象。