instances = ['XYZ']
curr_date = time.strftime("%Y%m%d")
for inst_name in instances:
with open(f'results_{inst_name}_master.csv') as f:
pkt_name = f.readline().split(';')[1]
print(f"package name is: {pkt_name}")
run_dt = f.readline().split(';')[1]
print(f"run date: {run_dt}")
time_check = f.readlines()[1].split(';')[-5].split(':')[0]
print(f"time is : {time_check}")
if ((run_dt == curr_date) or (run_dt < curr_date and time_check in range(20,24))):
for index, l in enumerate(f, 1):
if 'remoteInstallation' in l:
print(l)
示例檔案:
pktName;sample-quality.zip;
RunDate;20220116;
sample:path_to_test\test;20220116;01:29:13;20220114;01:33:36;0:04:22;
;sample:path\to\remoteInstallation;45.99;../logs_path/index.html;OK;
;sample:path\to\remoteInstallation;42.87;../logs__other_path/index.html;1
我得到了除 之外的所有結果print(l),也就是說,盡管檔案中存在字串:'remoteInstallation',但它無法遍歷檔案。
請注意,實際上,該檔案在每一行的末尾都包含換行符(\n)。
我在這里做錯了什么?
提前致謝!
uj5u.com熱心網友回復:
看來您正在使用readlines()而不是.readline()在 time_check 行上。
import time
instances = ['XYZ']
curr_date = time.strftime("%Y%m%d")
for inst_name in instances:
with open(f'results_{inst_name}_master.csv') as f:
pkt_name = f.readline().split(';')[1]
print(f"package name is: {pkt_name}")
run_dt = f.readline().split(';')[1]
這條線似乎不正確。它呼叫readlines并參考第一個索引處的元素。我洗掉了s和索引參考。
time_check = f.readline().split(';')[-5].split(':')[0]
print(f"time is : {time_check}")
if ((run_dt == curr_date) or (run_dt < curr_date and time_check in range(20,24))):
for index, l in enumerate(f, 1):
if 'remoteInstallation' in l:
print(l)
幕后發生了什么?
對于檔案物件(在這種情況下f),有一個內部指標可以跟蹤腳本當前在檔案中的位置。這個指標是通用的,被多個函式和 for 回圈使用。
每次呼叫readline()都會從檔案中讀取一行并將指標移動到下一行。任何呼叫都readlines()將讀取所有行,直到檔案末尾并將指標移動到檔案末尾。For 回圈讀取下一行(如果有的話)并不斷重復該程序,直到指標位于檔案末尾。在我們的代碼中,這一行:
for index, l in enumerate(f, 1):
是一個試圖從檔案中讀取更多行的 for 回圈。
不幸的是,在我們的例子中,通過呼叫readlines(),我們已經從檔案中讀取了所有行,并且已經將指標移動到了檔案的末尾,因此 for 回圈無法讀取任何新行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/412103.html
標籤:
上一篇:Pythonstr未列出
