Python 里面的 f.truncate() 问题

2011-07-02 02:04:20 +08:00
 dimlau
系统自带的 2.7 版本:
-----------------------
def print_a_line(f):
....for i in [1,2,3]:
........print("line %s: %s" % (i, f.readline()))
........f.truncate()

current_file = open(input_file,"w+")
current_file.write('''xxx.
yyy.
zzz.''')
current_file.seek(0)

print("Let's print three lines:")
print_a_line(current_file)
-----------------------

结果得到:
-----------------------
Let's print three lines:
line 1: xxx.

line 2:
line 3:
-----------------------

相同文件在版本 3.2 执行后得到:
-----------------------
Let's print three lines:
line 1: xxx.

line 2: yyy.

line 3: zzz.
-----------------------

肿么回事?我在读 Dive into Python ,翻看 2to3 那节也没看到说这个版本差异啊…
6796 次点击
所在节点    问与答
9 条回复
dimlau
2011-07-02 02:05:43 +08:00
呃…缩进那里没写错,不过编辑器吃掉了。
reus
2011-07-02 06:59:46 +08:00
是个bug吧
dimlau
2011-07-02 09:39:29 +08:00
呃…这么明显的 bug 啊,连我都能发现?
reus
2011-07-02 09:49:13 +08:00
其实两个f的类型是不一样的,一个是file,一个是_io.TextIOWrapper,文档的说法是两者是一样行为的,但实际不一样,那就是bug了
fanzeyi
2011-07-02 09:49:32 +08:00
In [10]: current_file.readline()
Out[10]: 'xxx. \n'

In [11]: current_file.readline()
Out[11]: ''

In [12]: current_file.readline()
Out[12]: ''

In [14]: !cat test
xxx.

// 这个文件里面就只有 xxx. - - 应该说是 write 的问题把..
fanzeyi
2011-07-02 09:53:40 +08:00
哦 我错了 是 truncate 的问题..


In [4]: current_file.seek(0)

In [5]: !cat hi
xxx.
yyy.
zzz.
In [6]: print("Let's print three lines:")
Let's print three lines:

In [7]: print_a_line(current_file)
line 1: xxx.

line 2:
line 3:

In [8]: !cat hi
xxx.
fanzeyi
2011-07-02 09:58:53 +08:00
哦..
根据 http://docs.python.org/library/stdtypes.html?highlight=file#file.truncate

你第一次执行到 xxx. 后面 然后执行截断 此时截断无参数 以当前指针在的位置截断..
fanzeyi
2011-07-02 10:03:06 +08:00
然后没在 3.2 的文档里面找到这个 【没学过3.* 无力了.. 】
dimlau
2011-07-02 13:13:21 +08:00
@fanzeyi 其实我就是说 3.x 的结果不是预料之中的,2.x 的那个是我想要的结果。
4楼 @reus 哦,我明白了,谢谢。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/15218

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX