Python文件.tell()给出错误的值

2024-05-23 19:28:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Windows7 64字节中使用Spyder2.3.7和Python2.7.10。你知道吗

我想读一个文件的文本,并且想读一行后在文件中的位置;主要原因是以后能够在文件中移回一些搜索完成后。 不管怎样,当我使用以下代码时:

FileOrig = "testtext{Number}";
for index_file in range(1, 2):
    fileName = FileOrig.format(Number = str(index_file))

    ff = open(fileName, "rb")
    numline = 1;
    for line in ff: 
        numline = numline + 1;
        position = ff.tell();
        print(position);

    ff.close()

其中testtext1文件的内容是(这只是一个示例):

Overall accuracy
Overall accuracy
2.2603e+03
2.3179e+03
2.5265e+03
4.8463e+03
1.7547e+03
3.0143e+03
3.1387e+03


Overall accuracy
Overall accuracy
2.2414e+03
3.9409e+03
1.8902e+03
4.1157e+03


Overall accuracy
Overall accuracy
2.2275e+03
1.3579e+03
2.3712e+03
6.4970e+03
5.8891e+03



    SPLITBIB.STY     -- N. MARKEY <markey@lsv.ens-cachan.fr>
                    v1.17 -- 2005/12/22

This package allows you to split a bibliography into several categories
and subcategories. It does not depend on BibTeX, and any bibliography
may be split and reordered.

split­bib – Split and re­order your bib­li­og­ra­phy

This pack­age en­ables you to split a bib­li­og­ra­phy into sev­eral cat­e­gories and sub­cat­e­gories. It does not de­pend on BibTeX: any bib­li­og­ra­phy may be split and re­ordered.

这就产生了非常奇怪的结果:

916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916
916

上面的代码有什么问题,如果我使用二进制读取与否没有什么不同。你知道吗


Tags: and文件代码numberphylirasplit
1条回答
网友
1楼 · 发布于 2024-05-23 19:28:47

在文件上混合迭代和使用文件方法将不起作用,因为迭代涉及使用预读缓冲区。用^{}代替file.tell

...
while True:
    line = ff.readline()
    if not line:
        break
    numline = numline + 1
    position = ff.tell()
    print(position)
...

根据^{} documentation

A file object is its own iterator, for example iter(f) returns f (unless f is closed). When a file is used as an iterator, typically in a for loop (for example, for line in f: print line.strip()), the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit when the file is open for reading (behavior is undefined when the file is open for writing). In order to make a for loop the most efficient way of looping over the lines of a file (a very common operation), the next() method uses a hidden read-ahead buffer. As a consequence of using a read-ahead buffer, combining next() with other file methods (like readline()) does not work right. However, using seek() to reposition the file to an absolute position will flush the read-ahead buffer.

相关问题 更多 >