![](/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.