簡體   English   中英

如何獲取要打開的文件的文件名和要保存在python中的文件的文件名

[英]How do I get the filename of a file to open and the filename of a file to save in python

我為標題不清楚而感到抱歉,我真的不知道該怎么寫,但是我正在嘗試用python創建文本編輯器。 我想獲取用戶打開或保存在python中的文件的文件名:

def openFile():
    file = filedialog.askopenfile(parent=main_window, mode='rb', title='Select a file')
    contents = file.read()
    textArea.delete('1.0', END)
    textArea.insert('1.0', contents)
    file.close()

用戶在這里會看到一個對話框,以選擇要打開的文件。 但是,如何獲得他選擇的文件的文件名?

def saveFileas():
    file = filedialog.asksaveasfile(mode='w')
    data = textArea.get('1.0', END+'-1c')
    file.write(data)
    file.close()

用戶在此處獲得一個對話框來保存他的文件,並輸入他們想要的名稱。 同樣,我需要用戶輸入的名稱。 兩者都使用默認的窗口打開保存對話框。

這是我所有的代碼:

from tkinter import Tk, scrolledtext, Menu, filedialog, END

main_window = Tk(className = " Text Editor")
textArea = scrolledtext.ScrolledText(main_window, width=100, height=80)

# def newFile():
def openFile():
    file = filedialog.askopenfile(parent=main_window, mode='rb', title='Select a file')
    contents = file.read()
    textArea.delete('1.0', END)
    textArea.insert('1.0', contents)
    file.close()


def saveFileas():
    file = filedialog.asksaveasfile(mode='w')
    data = textArea.get('1.0', END+'-1c')
    file.write(data)
    file.close()

def saveFile():
    content = textArea.get('1.0', END+'-1c')
    if content:
        print("There is content")
    else:
        print("There is no content")


#Menu options
menu = Menu(main_window)
main_window.config(menu=menu)
fileMenu = Menu(menu)
menu.add_cascade(label="File", menu=fileMenu)
fileMenu.add_command(label="New")
fileMenu.add_command(label="Open", command=openFile)
fileMenu.add_command(label="Save As", command=saveFileas)
fileMenu.add_command(label="Save", command=saveFile)
fileMenu.add_separator()
fileMenu.add_command(label="Print")
fileMenu.add_separator()
fileMenu.add_command(label="Exit")

textArea.pack()

main_window.mainloop()

這樣的事情應該可以獲取文件名。

  from  tkinter import filedialog
  root = Tk()
  root.filename =  filedialog.askopenfilename(initialdir = "Path Where the dialog should open first",title = 
  "Title of the dialog",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
  print (root.filename)
  root.withdraw()

文檔似乎暗示askopenfile返回文件名(如果已選擇文件名),或者返回空字符串(如果用戶單擊“取消”)。 換句話說,它是一個字符串,而不是文件指針。 您需要先打開文件。

askopenfile返回文件對象的句柄,就像Brian Oakley所說的那樣,您可以像這樣獲得文件名:

filePath = filedialog.askopenfile(parent=main_window, mode='rb', title='Select a file')
fileName = filePath.name.split('/').pop()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM