使用Python中的write()写入文件不能按预期工作

时间:2015-08-28 15:48:30

标签: python io

如果条件为真,我有一个非常简单的脚本可以将一行写入文件。 脚本满足条件但不是将行写入文件。这个问题是什么?

 #! /usr/bin/env python

 import sys
 import re
 import os
 import subprocess

 curdir = os.getcwd()

 files = os.listdir(curdir)

 newpbsname = curdir.split("/")
 GROUP = []
 for i in files:
     if i.endswith(".rst"):
         rstf.append(i)
 for G in files:
     if G.startswith("ti"):
         GROUP.append(G)

 GROUPS  = sorted(GROUP)

 num = int(GROUPS[-1][-8:-6])

 OP = open(GROUPS[-1],"r")
 filn = str(GROUPS[1][0:4]) + "%d" % (num+1) + ".group"
 OT = open(filn,"w")
 if GROUPS[-1][2] == 1 :
     A = " -O -i run0_03.in -p merged_21.prmtop -c restrt0-ti_21_%d.rst   -ref merged_21.inpcrd" % (num-1)
     print A
     OT.write(A + "\n")

1 个答案:

答案 0 :(得分:1)

您忘了关闭该文件。调用long timeout, TimeUnit unit时,文件系统中会生成所需的文件,但由于文件系统未关闭,因此文件系统没有内容。通过调用OT.write(),文件将关闭,其内容将写入文件系统,如以下控制台输出所示:

OT.close()

所以代码的最后一部分应该是:

# init a file object in python
In [7]: f = open('foo.txt', 'w')

# write a sample string to the file object (IPython's output shows the bytes written)
In [8]: f.write('foo')
Out[8]: 3

# viewing foo.txt using cat does not deliver any contents
In [10]: cat foo.txt

# ll shows that foo.txt does not have any filesize
In [11]: ll
0 28 Aug 19:05 foo.txt

# close the file (file object) and see what happens
In [12]: f.close()

# after closing the file object f, cat delivers the desired output
In [13]: cat foo.txt
foo

# and ll shows that the filesize is three bytes
In [14]: ll
total 32
3 28 Aug 19:06 foo.txt

然而,打开和关闭要写入的文件似乎有点烦人。您可以使用 if GROUPS[-1][2] == 1 : A = " -O -i run0_03.in -p merged_21.prmtop -c restrt0-ti_21_%d.rst -ref merged_21.inpcrd" % (num-1) print A OT.write(A + "\n") OT.close() # added this line 而不是使用.open().close(),如下所示:

open(filename, mode) as f

这会在执行with open(filn,"w") as OT: if GROUPS[-1][2] == 1 : A=" -O -i run0_03.in -p merged_21.prmtop -c restrt0-ti_21_%d.rst -ref merged_21.inpcrd" % (num-1) print A OT.write(A + "\n") 语句下面的内容之前打开文件,并在完成这些操作后自动关闭它。