簡體   English   中英

python中seek()和split()的不穩定(看似隨機)行為

[英]Erratic (seemingly random) behavior of seek() and split() in python

考慮以下代碼:

import sys
with open(sys.argv[1]) as data_file:
   data_file.readline() #skipping lines of texts
   data_file.readline()
   data_file.readline() #skipping lines of texts
   data_file.readline()
   data_file.readline() #skipping lines of texts
   data_file.readline() #skipping lines of texts
   data_file.readline() #skipping lines of texts
   data_file.readline() #skipping lines of texts
   data_file.readline() #skipping lines of texts
   while True:
       print "#"
       pos=data_file.tell()
       next_mol=data_file.readline().split()
       print next_mol
       data_file.seek(pos)
       print data_file.readline().split()

sys.argv [1]是文本文件的名稱,其中包含以下數據:

ITEM: TIMESTEP
31500000
ITEM: NUMBER OF ATOMS
28244
ITEM: BOX BOUNDS pp pp pp
0.706774 63.6072
1.77317 62.6918
-4.27518 67.4572
ITEM: ATOMS id type x y z 
1 1 8.07271 20.6394 38.953 
2 1 7.45444 20.2706 37.5682 
3 1 7.94593 21.3438 36.5822 
4 2 8.88701 22.2414 37.422 
5 6 8.97587 21.7898 38.6976 
6 7 9.51512 23.1098 36.8675 
7 1 9.83459 22.2787 39.7728 
8 3 8.54346 19.7726 39.3733 
9 3 7.3188 20.9572 39.6053 
10 3 6.33686 20.2798 37.6457 
11 3 7.62824 19.2464 37.1935 
12 3 7.14438 21.9616 36.2781 
13 3 8.4454 20.9589 35.6742 
14 3 9.51704 23.2023 40.2712 
15 3 10.839 22.4705 39.342 
16 3 9.84061 21.5031 40.5668 

給我以下輸出:

#
['1', '1', '8.07271', '20.6394', '38.953']
['71', '20.6394', '38.953']
#
['2', '1', '7.45444', '20.2706', '37.5682']
['1', '7.45444', '20.2706', '37.5682']
#
['3', '1', '7.94593', '21.3438', '36.5822']
['1', '7.94593', '21.3438', '36.5822']
#
['4', '2', '8.88701', '22.2414', '37.422']
['2', '8.88701', '22.2414', '37.422']
#
['5', '6', '8.97587', '21.7898', '38.6976']
['6', '8.97587', '21.7898', '38.6976']
#
['6', '7', '9.51512', '23.1098', '36.8675']
['7', '9.51512', '23.1098', '36.8675']
#
['7', '1', '9.83459', '22.2787', '39.7728']
['1', '9.83459', '22.2787', '39.7728']
#
['8', '3', '8.54346', '19.7726', '39.3733']
['3', '8.54346', '19.7726', '39.3733']
#
['9', '3', '7.3188', '20.9572', '39.6053']
['3', '7.3188', '20.9572', '39.6053']
#
['10', '3', '6.33686', '20.2798', '37.6457']
['0', '3', '6.33686', '20.2798', '37.6457']

我期望'#'之間的兩個字符串相同。 我在這里想念什么嗎?

file.readline()使用file.readline() 讀緩沖區查找換行符,因此它可以為您返回以\\n結尾的簡潔行。 另一種方法是逐字節讀取直到找到換行符,這將是非常低效的。

這樣,您的第一個file.readline()從文件中讀取大量信息,解析出第一行並將其返回。 然后,對file.readline()的下一次調用很可能能夠單獨從緩沖區中給您下一行,等等。

while循環時,預讀緩沖區已填充了最多1 1 8.072ITEM: ATOMS id type xyz行之后的ITEM: ATOMS id type xyz一個字節)中的所有內容。 然后,下一個file.readline()調用讀取更多緩沖區以查找另一個換行符,將文件位置移動到下一行的開頭2之后, file.readline()

您不能可靠地從文件中獲取正確的文件位置使用file.readline()調用; 您必須考慮讀取的行數,實際的緩沖區大小以及文件中使用的行分隔符的樣式。 您的問題幾乎可以肯定以不同的方式解決,例如將已讀取的行存儲在隊列或某種堆棧中,以供循環的后續迭代中使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM