![](/img/trans.png)
[英]How to choose multiple files from file dialog and open at the same time and access them
[英]How to open and manipulate multiple text files all at the same time after selecting them with tkinter?
Python noob在这里:
我试图通过使用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(不是复数)一起使用,并且我可以删除不需要的字符串。
任何提示将不胜感激!
您没有使用列表中的每个文件名。 因此,相反,您需要对通过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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.