2012-07-02 49 views
1

我正在使用Windows 7和Python 2.7.3。仍然是关于python文件操作

PS C:\Python27\LearnPythonTheHardWay> python 
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win 
32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> input = open('file_operation_sample.txt', 'a+') 
>>> print input.tell() # first 'tell()' 
0 
>>> input.write(u'add') 
>>> print input.tell() 
12 
>>> input.seek(0) 
>>> print input.read() 
123456789add 
>>> input.close() 
>>> 

我很不解,为什么第一tell()打印0(我认为这将输出9)? 'a +'是一个附加模式,文件指针应该在EOF处。而且我更困惑,最后字符串'abc'被追加到'123456789'?

另一个问题,

PS C:\Python27\LearnPythonTheHardWay> python 
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win 
32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> from io import open 
>>> input = open('file_operation_sample.txt', 'a+') 
>>> print input.tell() 
9 
>>> input.write(u'add') 
3L 
>>> print input.tell() 
12 
>>> input.seek(2) 
2 
>>> input.seek(2, 1) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
IOError: can't do nonzero cur-relative seeks 
>>> 

什么问题?如果我注释掉from io import open,它会没事的。

+0

最后一个问题可能是一个错误,请参阅http://www.gossamer-threads.com/lists/python/dev/764284 – Kos

回答

1

Python的tell()的行为与C的ftell()相同。该documentation here笔记:

注意,当一个文件被打开追加数据,当前文件位置由最后一个I/O操作来决定,而不是由哪里会发生下一次写。

这可以解释为什么你的第一个讲的是0 - 你有没有做过任何文件I/O呢。


下面是一个例子。首先,我们将向该文件写入5个字符。正如我们所期望的那样,当我们完成时,写入开始于0并且文件指针在5处。

>>> with open('test.txt', 'w') as fh: 
    fh.write('12345') 
    fh.tell() 

5L 

现在我们打开它来追加。正如您发现的,我们从0开始。但是现在我们从文件中执行read(),而不是太惊奇,我们从0开始阅读。读取之后,文件指针已移至5

>>> with open('test.txt', 'a+') as fh: 
    fh.tell() 
    fh.read() 
    fh.tell() 

0L 
'12345' 
5L 

好吧,让我们打开文件进行追加,然后执行写操作。正如文档所述,在写入之前,文件指针被移动到文件的末尾。因此,即使在写入之前文件指针为0,我们仍会在旧的字节之后得到新的字节。

>>> with open('test.txt', 'a+') as fh: 
    fh.tell() 
    fh.write('abc') 
    fh.tell() 
    fh.seek(0) 
    fh.read() 

0L 
8L 
'12345abc' 

对Python的seek()的文件也暗示了这种行为:

注意,如果打开文件进行追加(模式 'a' 或 'A +'),任何 寻求()操作将在下次写作时撤消。

+0

那么这是什么意思:'(当一个文件被打开追加,在执行任何写入操作之前,文件的位置将移动到文件的结尾。)'(文档页面括号中的单词)? – imsrch

+0

@Kos我看到..... – imsrch

+0

@ user1477871它在写操作之前移动到文件的末尾* - 意味着在你进行函数调用之后。我会用一些示例代码更新我的答案。 – JoeFish