我正在用 python 讀取 15GB 的檔案,我的代碼如下所示:
infile = open(file, "r")
count=0
line = infile.readline()
num_lines = int(sum(1 for line in open(file)))
while line:
if count%2==0:
if count>num_lines:
break
fields=line.split(";")
tr=int(fields[0].split(",")[1])
for ff in fields[1:]:
ffsplit=ff.split(",")
address=int(ffsplit[0])
amount=int(ffsplit[1])
if address not in add_balance.keys():
add_balance[address]=-amount
else:
add_balance[address]-=amount
if address not in de_send.keys():
de_send[address]=1
else:
de_send[address] =1
else:
fields=line.split(";")
for ff in fields:
ffsplit=ff.split(",")
address=int(ffsplit[0])
amount=int(ffsplit[1])
if address not in add_balance.keys():
add_balance[address]=amount
else:
add_balance[address] =amount
if address not in de_rec.keys():
de_rec[address]=1
else:
de_rec[address] =1
count =1
line=infile.readline()
現在,當 tr 在某個范圍內([100000,200000]、[200000,300000] 等)時,我需要在該范圍內創建一個 networkX 圖(將范圍內的 tr 和地址添加為節點)并執行一些其他操作同時還在更新字典。
tr 像索引一樣作業,所以每兩行從 1 開始(這就是 的原因count%2==0)增加 1
我試圖創建一個def createGraph,同時讀取檔案也會在該范圍內創建節點。我的問題是,每次創建圖形時,我都會從頭開始讀取檔案,因此顯然它的計算效率不高。
我如何從某個 tr(假設為 100000)開始,在 whlie 子句中每 100000 tr 創建一個圖?
uj5u.com熱心網友回復:
如果檔案永遠不會改變,您可以使用.tell預先計算所需行的位置,然后使用 .seek 方法移動到該行并從那里開始作業
>>> with open("test.txt","w") as file: #demostration file
for n in range(10):
print("line",n,file=file)
>>> desire_line=4
>>> position_line=0
>>> with open("test.txt") as file: #get the line position
for i,n in enumerate(iter(file.readline,"")):
if i==desire_line:
break
position_line=file.tell()
>>> with open("test.txt") as file:
file.seek(position_line)
for line in file:
print(line)
40
line 5
line 6
line 7
line 8
line 9
>>>
如果檔案確實發生了變化,特別是在您想要的點之前的行中,這會弄亂搜索,您可以使用 itertools 模塊來幫助您到達那里
>>> import itertools
>>> with open("test.txt") as file:
for line in itertools.islice(file,5,None):
print(line)
line 5
line 6
line 7
line 8
line 9
>>>
有關更多選擇,請查看此答案
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/374427.html
下一篇:Java中如何將文本轉換為物件
