从用户获取长文件名的规范方法

时间:2018-02-28 13:37:29

标签: python python-3.x

我正在编写一个Python模块,它将读取和分析专用软件程序的输入文件。我希望用户能够分析他们选择的任何输入文件。到目前为止,我已经尝试了两种方法来获取文件名:

方法1:

filename = input('File to be analyzed: ')

Pro:最简单的方法

骗局:用户每次都难以输入长文件路径

方法2:

将名为path.txt的文件放在与Python模块相同的目录中,用户可以在那里存储文件名。

    import os

    pathtxt_dir = os.path.dirname(os.path.realpath(__file__))
    pathtxt_fullpath = os.path.join(pathtxt_dir, 'path.txt')
    try:
        fo = open(pathtxt_fullpath, 'r')
        lines = fo.readlines()
        fo.close()
    except IOError:
        raise Exception('path.txt cannot be opened')
    filename = lines[0].rstrip().lstrip()  # input file

Pro:同事熟悉这种方法,因为它与之前使用过的程序类似。

Con:这似乎是一种不必要的复杂方式来获取用户输入

问题:

是否有规范的Python方法来获取长文件和重复的用户输入,例如此文件名?还有,我还没有考虑过另一种有用的方法吗?

1 个答案:

答案 0 :(得分:0)

您可以使用tkinter打开GUI来选择文件。这样他们每次都不必打字。

import tkinter as tk
from tkinter import filedialog as fd
import os


def getfile(title='Choose files', sformat='.*'):
    root = tk.Tk()
    root.lift()  

    # d and f are whatever default directory and filename        

    try:
        f = fd.askopenfilename(parent=root, title=title, filetypes=[('', sformat)], initialdir=d, initialfile=f)
        root.withdraw()
        return f
    except:
        # print(title + ': error - no file exists')
        return ''
相关问题