简体   繁体   English

Python文件路径和名称检索

[英]Python file path and name retrieval

Alright so I've made a save as button in python and was wondering how do I retrieve the file path from where it was saved. 好吧,所以我在python中做了一个另存为按钮,想知道如何从保存位置检索文件路径。 I also was wondering if the name is changed during saving how to know what that is. 我也想知道在保存过程中是否更改了名称,如何知道那是什么。 If I try to call the file name in a different .py file I receive a error code. 如果尝试在其他.py文件中调用文件名,则会收到错误代码。 Code for the button is below 该按钮的代码如下

Thanks 谢谢

import tkinter, tkinter.constants, tkinter.filedialog

class tkFile(tkinter.Frame):

    def __init__(self, root):

        tkinter.Frame.__init__(self, root)
        button_opt = {'fill': tkinter.constants.BOTH, 'padx': 5, 'pady': 5}
        tkinter.Button(self, text='Save As',command=self.asksaveasfilename).pack(**button_opt)

        self.file_opt = options = {}
        options['filetypes'] = [('all files', '.*'), ('csv files', '.csv')]
        options['initialfile'] = 'data.csv'
        options['parent'] = root

    def asksaveasfilename(self):
        filename = tkinter.filedialog.asksaveasfilename(**self.file_opt)

        if filename:
            return open(filename, 'w')

if __name__=='__main__':
    root = tkinter.Tk()
    tkFile(root).pack()
    root.mainloop()

The code that I want to call the name into is below. 我想将其命名为的代码如下。 Specifically I'm looking to call the name from the save as button to a different file. 具体来说,我想将名称从“另存为”按钮调用到另一个文件。 The error code states self in undefined. 错误代码将self声明为undefined。

name = savePathButton.tkFile.asksaveasfilename(self)

name 'self' is not defined

You can import os , and use os.path.dirname(os.path.realpath(__file__)) to retrieve the file location. 您可以import os ,并使用os.path.dirname(os.path.realpath(__file__))来检索文件位置。

For the actual file name, you could use os.listdir(os.getcwd()) which would return a list of file names within the directory. 对于实际的文件名,您可以使用os.listdir(os.getcwd()) ,它将返回目录中的文件名列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM