[英]How to open and manipulate multiple text files all at the same time after selecting them with tkinter?
Python noob here: Python noob在这里:
I am trying to speed up my file-editing through selecting multiple text files with tkinter, but I don't know how to open them and edit them all at once to remove <_io.TextIOWrapper name='xyz.txt' mode='w' encoding='UTF-8'>
我试图通过使用tkinter选择多个文本文件来加快文件编辑的速度,但是我不知道如何打开它们并立即对其全部进行编辑以删除
<_io.TextIOWrapper name='xyz.txt' mode='w' encoding='UTF-8'>
My code: 我的代码:
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()
It works with askopenfilename (not plural) and I remove the unwanted string just fine. 它可以与askopenfilename(不是复数)一起使用,并且我可以删除不需要的字符串。
Any hint would be appreciated! 任何提示将不胜感激!
You are not working with each file name within the list. 您没有使用列表中的每个文件名。 So instead you need to run a for loop over your list created from
askopenfilenames()
. 因此,相反,您需要对通过
askopenfilenames()
创建的列表运行for循环。
According to the tooltip in my IDE askopenfilenames()
returns a list. 根据我的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()
I changed your variable filename to filenames as it is a list and this makes more sense. 我将您的变量文件名更改为文件名,因为它是一个列表,这更有意义。 Then I ran a for loop over this list and it should work as desired.
然后,我在该列表上运行了一个for循环,它应该可以正常工作。
Try this below code. 试试下面的代码。
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()
With a couple of if statements we can prevent the most common errors that may come up if you select nothing or select file types that are not compatable. 使用几个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.