【问题标题】:TKinter User Input into OS Walk - Get user input to pull File NameTKinter 用户输入到 OS Walk - 获取用户输入以提取文件名
【发布时间】:2016-06-20 11:58:54
【问题描述】:

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

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

配置解析器/用户输入

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

问题是我可以根据用户输入分解结构(即在 Alpha 结构中读取“aoth”,按两个文件夹分解)。然而 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 将 file[:1]/file[:3] 视为文字输入。我如何让用户输入读取实际的文件名并相应地分解?我敢肯定,我错过了一些非常简单的东西。

感谢您阅读本文!

【问题讨论】:

  • 什么是“文件名分解结构”?
  • 另外,这很奇怪:Entry.get(self.sourceE) -- 你为什么不打电话给self.sourceE.get()?
  • 让我详细说明。用户想要将文件从源文件夹移动到目标文件夹。使用选项对话框,他在三个选项之间进行选择。选项A按文件名的第一个字母排序(A/Alpha.tiff),选项B按First然后后两个排序(C/CH/Chicken.jpg),最后选项C允许用户输入自己的.我无法让选项 C 的 self.radio_aBoxV.get() 将输入视为实际文件变量。
  • 是的,我还没来得及修复那部分 :) 但这还不是问题。
  • 这句话毫无意义:“我无法让选项 C 的 self.radio_aBoxV.get() 处理输入” - 单选按钮不“处理输入” .它拥有一个价值,仅此而已。你是说它返回错误的值吗? self.radio_aBoxV.get()返回什么?

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


【解决方案1】:

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

"file[:1],file[:2]" 与 file[:1],file[:2] 不同。

您的前两个选项是硬编码的,因此他们使用 reference 文件 并对其应用 slice notation。最后一个接受一个 String 并扔掉它;该程序不知道您的意思是将 String "file" 转换为 Reference file 和 String "[:1]" 并将其转换为 slice notation [:1].

问题的解决方案是进行转换,可能是通过进入 String 并从中提取必要的信息。您这样做是为了获得分区的数量,但永远不要转换 reference 和 slice 表示法。您可以使用代码中的那些分区并使用 split 或 slice notations 进行一些优化以“删除”重要部分,但我建议使用 Regex (Python 中的 re 模块),因为它是一种更灵活的解决方案。

Python RE HowTo

以下是我主要工作的示例;我有一个评论可能会导致它给出不完美的结果(同时否定开始和步进),但这是一个非常模糊的情况,您可以通过删除选项来获得高达 100% 的代码使用切片符号的 step 部分。您还会注意到,只是盲目地从用户那里获取切片符号可能会导致目录名称格式错误。

(注意——我实际上并没有在 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'

【讨论】:

  • 再看一下我的代码,您还可以使用逻辑树来根据re 从字符串中提取的内容来确定如何编写切片符号;即-if start: if end and step: index[start:end:step];elif end: file[start:end] _etc_。这当然是可行的,并且可以解决一个不好的情况,但这似乎更加精简且易于解决。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-06
  • 2019-04-16
  • 1970-01-01
相关资源
最近更新 更多