【问题标题】:How to open and manipulate multiple text files all at the same time after selecting them with tkinter?使用 tkinter 选择多个文本文件后,如何同时打开和操作多个文本文件?
【发布时间】:2019-01-02 09:30:52
【问题描述】:

这里是 Python 菜鸟:

我正在尝试通过使用 tkinter 选择多个文本文件来加快文件编辑速度,但我不知道如何打开它们并一次编辑它们以删除 <_io.TextIOWrapper name='xyz.txt' mode='w' encoding='UTF-8'>

我的代码:

import re
from Tkinter import *
from tkFileDialog import askopenfilenames

filename = askopenfilenames()

f = open(filename, "r")

lines = f.readlines()

f.close()

f = open(filename, "w")

for line in lines:
    line = re.sub('<(.|\n)*?>', "", line)
    f.write(line)

f.close()

它适用于 askopenfilename(不是复数),我可以很好地删除不需要的字符串。

任何提示将不胜感激!

【问题讨论】:

    标签: python regex python-3.x file tkinter


    【解决方案1】:

    您没有使用列表中的每个文件名。因此,您需要对从 askopenfilenames() 创建的列表运行 for 循环。

    根据我的 IDE 中的工具提示 askopenfilenames() 返回一个列表。

    def askopenfilenames(**options):
        """Ask for multiple filenames to open
    
        Returns a list of filenames or empty list if
        cancel button selected
        """
        options["multiple"] = 1
        return Open(**options).show()
    

    我将您的变量文件名更改为文件名,因为它是一个列表,这更有意义。然后我在这个列表上运行了一个 for 循环,它应该可以按需要工作。

    试试下面的代码。

    import re
    from Tkinter import *
    from tkFileDialog import askopenfilenames
    
    filenames = askopenfilenames()
    
    for filename in filenames:
        f = open(filename, "r")
    
        lines = f.readlines()
    
        f.close()
    
        f = open(filename, "w")
    
        for line in lines:
            line = re.sub('<(.|\n)*?>', "", line)
            f.write(line)
    
        f.close()
    

    通过几个 if 语句,我们可以防止在您不选择任何内容或选择不兼容的文件类型时可能出现的最常见错误。

    import re
    from Tkinter import *
    from tkFileDialog import askopenfilenames
    
    filenames = askopenfilenames()
    
    if filenames != []:
        if filenames[0] != "":
            for filename in filenames:
                f = open(filename, "r")
    
                lines = f.readlines()
    
                f.close()
    
                f = open(filename, "w")
    
                for line in lines:
                    line = re.sub('<(.|\n)*?>', "", line)
                    f.write(line)
    
                f.close()
    

    【讨论】:

    • @Waldkamel 很高兴为您提供帮助。请选中我的答案旁边的复选标记以表明您的问题已解决。
    • 如果我可以问,您使用的是哪个 IDE?工具提示中的这些额外信息将对我的学习过程非常有帮助!
    • 带有 Pydev 插件的 Eclipse。
    • 再次感谢!我会确保下载它。复选标记被选中:-)
    猜你喜欢
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2021-07-25
    相关资源
    最近更新 更多