TKinter用户输入OS Walk - 获取用户输入以提取文件名

时间:2016-06-20 11:58:54

标签: python-2.7 tkinter user-input configparser os.walk

这很难总结我想要做的事情,我怀疑标题让它更容易理解但是......

我正在使用tkinter构建一个选项对话框,允许用户输入自己的文件名分解结构。 Os.Walk将根据用户输入读取和设置文件夹结构。

配置解析器/用户输入

[Alpha] aoth = file[:1], file[:3]

问题在于我可以根据用户输入细分结构(I.E Read' aoth'在Alpha结构中,按两个文件夹分解)。但是,Os.Walk / Python将此视为实际输入。打破代码只显示相关信息:

for root, subFolders, files in os.walk(Entry.get(self.sourceE)):
    for file in files:
        if not file.startswith('.'):
            if file[0].isalpha():
                alpfol = '%s' % self.alpha_fol.get()
                alset = self.alphaa_radio.get()
                if alset == 1:
                    file_strut = '%s' % file[:1]
                elif alset == 2:
                    file_strut = '%s/%s' % (file[:1], file[:2])
                elif alset == 3:
                    files_strip = [st.strip() for st in (self.radio_aBoxV.get()).split(',')]
                    files_count = len(files_strip)
                    ###
                    file_count_check = '%s/'*files_count
                    file_strut = file_count_check % tuple(files_strip)
                    ###
                subFolder = os.path.join(Entry.get(self.destE), alpfol, file_strut)
            checkFile = os.path.join(subFolder, file)
                ........

我知道它不是最优雅的代码,但是alset 1/2工作完美无缺,而alset 3认为文件[:1] / file [:3]是文字输入。如何让用户输入读取实际文件名并相应地分解?我确定它很简单,我很遗憾。

感谢您阅读本文!

1 个答案:

答案 0 :(得分:0)

好吧,就像你提出的那样,这是一个非常简单明显的错误:

  

"文件[:1],文件[:2]" 文件[:1]不同,文件[:2]

您的前两个选项是硬编码的,因此他们会将参考文件切片表示法应用于其中。最后一个采用 String 并将其抛出;程序不知道你是不是要将 String"文件" 转换为参考文件 String" [:1]" 并将其转换为切片表示法[:1]

问题的解决方案是进行转换,可能是进入字符串并从中提取必要的信息。这样做是为了获得分区数,但从不转换引用切片表示法。您可以在代码中使用这些分区,并使用 split slice notations 进行一些处理,以便" cut"重要的一点,但我会建议使用Regex(Python中的 re 模块),因为它是一个更灵活的解决方案。

Python RE HowTo

以下是我主要工作的样本;我在一点上发表评论可能会导致它给出不完美的结果(同时包括负面开始和步骤),但它是一个非常模糊的案例,你可以通过删除它来获得高达100%的代码选项以使用切片表示法的部分。您还会注意到,只是盲目地从用户处获取切片表示法可能会导致目录名称格式错误。

(注意 - 我实际上并没有在Python 2中编程,但据我所知这是2.7安全的;希望只需要进行必要的修改就可以进行微小的语法调整)

import os, os.path
import re

PATTERNRE=re.compile('''(?P<parts>[Ff]ile\[(?P<start>-?\d*):+(?P<end>-?\d*):?(?P<step>-?\d*)\])''')

def formatindices(start,end,step,file): ## Slice Notation only accepts Ints,
                                        ## and int('{empty string}') raises an error,
                                        ## so we're programming around it
    step = int(step) if step else 1
    if not start:
        if step>0: start=0
        else: start=-1
    else:
        start=int(start)
    end = int(end) if end else len(file) ## Having both negative Start and Step will
                                         ## break this on the else statement, couldn't
                                         ## find an integer to represent "index before 0"
    return start,end,step

files=['hello.py','world.pyc','helloworld.tar.gz.','foo.pyo','bar.pyo','foobar.whl']
patterns=['fl<;>','file[:]','file[:1],file[:2]','file[1:2]','file[:2],file[2:4]','file[:-3:2],file[:-2:-1],file[-1:]']

for i,(file,pattern) in enumerate(zip(files,patterns),start=1):
    try:
        if not file.startswith('.') and file[0].isalpha():
            print "Trial %d: %s=>%s" % (i,file,pattern)

            matches=PATTERNRE.finditer(pattern) ## Use Re to find all "file[x:y:z]"
            ## Convert to  list of tuples
            indices=[(match.group('start'),match.group('end'),match.group('step')) for match in matches]
            ## Using IOError because a lot that can otherwise go wrong comes up as
            ## ValueError (Which is the most-logical ErrorName)
            if not indices: raise IOError('Bad Formatting')

            ## Standardize indexes
            indices=[formatindices(start,end,step,file) for start,end,step in indices]
            print 'Indices: '+'|'.join(','.join(str(item) for item in startendstep) for startendstep in indices)

            ## Build File Structure
            file_strut='\\'.join(file[start:end:step] for start,end,step in indices)
            print 'Folder Structure: '+file_strut

            ## Put together
            subFolder = os.path.join('directoryfrom self.destE', 'somefolder alpfol', file_strut)
            print'Output: '+subFolder+'\n'
    except IOError:
        print 'No Pattern, Skipping\n'