V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
dimlau
V2EX  ›  问与答

Python 里面的 f.truncate() 问题

  •  
  •   dimlau · 2011-07-02 02:04:20 +08:00 · 6782 次点击
    这是一个创建于 4705 天前的主题,其中的信息可能已经有所发展或是发生改变。
    系统自带的 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 那节也没看到说这个版本差异啊…
    9 条回复    1970-01-01 08:00:00 +08:00
    dimlau
        1
    dimlau  
    OP
       2011-07-02 02:05:43 +08:00
    呃…缩进那里没写错,不过编辑器吃掉了。
    reus
        2
    reus  
       2011-07-02 06:59:46 +08:00
    是个bug吧
    dimlau
        3
    dimlau  
    OP
       2011-07-02 09:39:29 +08:00
    呃…这么明显的 bug 啊,连我都能发现?
    reus
        4
    reus  
       2011-07-02 09:49:13 +08:00
    其实两个f的类型是不一样的,一个是file,一个是_io.TextIOWrapper,文档的说法是两者是一样行为的,但实际不一样,那就是bug了
    fanzeyi
        5
    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
        6
    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
        7
    fanzeyi  
       2011-07-02 09:58:53 +08:00
    哦..
    根据 http://docs.python.org/library/stdtypes.html?highlight=file#file.truncate

    你第一次执行到 xxx. 后面 然后执行截断 此时截断无参数 以当前指针在的位置截断..
    fanzeyi
        8
    fanzeyi  
       2011-07-02 10:03:06 +08:00
    然后没在 3.2 的文档里面找到这个 【没学过3.* 无力了.. 】
    dimlau
        9
    dimlau  
    OP
       2011-07-02 13:13:21 +08:00
    @fanzeyi 其实我就是说 3.x 的结果不是预料之中的,2.x 的那个是我想要的结果。
    4楼 @reus 哦,我明白了,谢谢。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1980 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 16:08 · PVG 00:08 · LAX 09:08 · JFK 12:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.