美文网首页
Python 文件读取 with open() as f,ope

Python 文件读取 with open() as f,ope

作者: 顽强的猫尾草 | 来源:发表于2018-12-27 10:12 被阅读56次

Python 的文件读取有两个最基本的用法,其一 with open() as f,其二 open()配合close()。如果选择第一种,程序会自行关闭使用完的文件,而第二种则需要自己手动关闭。

从简便性上自然第一种逐渐替代了第二种,但是今天遇到了一个坑:

r = raw_input()
with open('/home/ubuntu/cppalg/input/input_chains.txt', 'w') as f:    # 打开 input_chains.txt
    while r != '#':
        f.write(r + '\n')
        r = raw_input()
print("All input received. MDP algorithm start...")
try:
    ret = subprocess.check_output("./../cppalg/main", shell=True)    # 在另外的程序中读取 input_chains.txt
    print  'res:', ret
except subprocess.CalledProcessError, exc:
    print 'returncode:', exc.returncode
    print 'cmd:', exc.cmd
    print 'output:', exc.output

发现调用的程序无法读取 input_chains.txt 这个文件,因为在使用 with open() as f 的方式读取文件结束后,没有给出明显的结束提示,程序就会在自己认为适当的时机关闭这个文件,但在此例中显然时机还是晚了。

改成传统的读取方式就没有问题了:

f = open('/home/ubuntu/cppalg/input/input_chains.txt', 'w')
while r != '#':
    f.write(r + '\n')
    r = raw_input()
f.close()
print("All input received. MDP algorithm start...")
try:
    ret = subprocess.check_output("./../cppalg/main", shell=True)
    print  'res:', ret
except subprocess.CalledProcessError, exc:
    print 'returncode:', exc.returncode
    print 'cmd:', exc.cmd
    print 'output:', exc.output

相关文章

网友评论

      本文标题:Python 文件读取 with open() as f,ope

      本文链接:https://www.haomeiwen.com/subject/wuollqtx.html