我有 4 個檔案夾,里面裝滿了 txt 檔案。我使用下面的代碼提取所有 txt 并將它們附加到串列中。
Doc1 = glob.glob('path*.txt')
Doc2 = glob.glob('path*.txt')
Doc3 = glob.glob('path*.txt')
Doc4 = glob.glob('path*.txt')
lines = []
for file in Doc1: ### repeated this block for Doc2, Doc3 and Doc4 ####
f = open(file,'r')
lines.append(f.readlines())
f.close()
上面的代碼作業得很好。但是,現在我想做的是:
- 對于檔案夾中的每個 txt 檔案,我只想在開始和結束之間添加行,以消除不必要的文本。對于所有檔案夾中的每個檔案,開始和結束文本都是相同的。我試圖這樣做:
for file in Doc1:
f = open(file,'r') #this opens the file
for line in file: #for each line in the file
tag = False #tag set to False, initially
if line.startswith('text'): #if it starts with this text then:
tag = True #tag changes to True
elif 'end text' in line: #if it this text is in the line then:
tag = False #tag stays false
lines.append(f.readlines()) #append this line (but now tag stays False)
elif tag: # if tag is true, then append that line
lines.append(f.readlines())
f.close()
此代碼運行,如我沒有收到任何警告或錯誤。但是沒有行附加到行。TIA 尋求任何建議和幫助。
uj5u.com熱心網友回復:
該標簽在每次迭代時都會重置,這意味著它永遠不會輸出除其中包含的行之外的任何end text內容。此外,還需要對操作進行一些重新排序。
lines = []
for p in Doc1:
tag = False # Set the initial tag to False for the new file.
with open(p, 'r') as f:
for line in f:
if tag: # First line will never be printed since it must be a start tag
lines.append(line)
if line.startswith('start'): # Start adding from next line
tag = True
elif 'end' in line: # Already added the line so we can reset the tag
tag = False
uj5u.com熱心網友回復:
這是因為您正在使用line, 是檔案,以字串形式,未讀取,為此您可以執行以下操作:
for line in f:
# write code here
所以你的代碼變成這樣:
import glob
Doc1 = glob.glob('path*.txt')
Doc2 = glob.glob('path*.txt')
Doc3 = glob.glob('path*.txt')
Doc4 = glob.glob('path*.txt')
lines = []
for file in Doc1:
f = open(file,'r') #this opens the file
for line in f: #for each line in the file
tag = False #tag set to False, initially
if line.startswith('text'): #if it starts with this text then:
tag = True #tag changes to True
elif 'end text' in line: #if it this text is in the line then:
tag = False #tag stays false
lines.append(f.readlines()) #append this line (but now tag stays False)
elif tag: # if tag is true, then append that line
lines.append(f.readlines())
f.close()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/410517.html
標籤:
