[英]readlines from iterating through an array and writelines to a new file
bad_list 是一個從不同函數返回的數組,返回有問題需要更仔細查看的行的行號
例如array([ 1, 3, 4, 27, 50, 99], dtype=int64)
這個想法是讀取 test.txt,並創建一個新的 test_badlines.txt,其中只包含 bad_list 中指定的有問題的行
這是我到目前為止所擁有的,打印行有效,但寫行只在應該是 6 行時吐出 1 行
for rows in bad_list:
filename = 'C:\\Users\\Username\\Downloads\\test.txt'
bad_filename = str(filename)[:-4] + '_badlines.txt'
with open(filename) as f, open(bad_filename, 'w') as wt:
lines = f.readlines()
#print lines[rows]
wt.writelines(lines[rows])
lines
是一個普通的list
,並且普通的list
不能通過要查找的索引序列進行索引。 這里最簡單的解決方案是制作一個生成器表達式來提取您關心的行,替換:
wt.writelines(lines[rows])
和:
wt.writelines(lines[row] for row in bad_list)
假設bad_list
是您所描述的數組,則完全刪除外部for
循環; 您不想每行一遍又一遍地打開輸入和輸出文件,總共只打開一次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.