user3975306
user3975306

Reputation:

Writing to file with write() in Python does not work as expected

I have a very simple script to write one line to a file if the condition is true. the script fulfill the condition but it is not writing the line to the file. whats the problem?

 #! /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")

Upvotes: 0

Views: 81

Answers (1)

albert
albert

Reputation: 8583

You forgot to close the file. When calling OT.write() the desired file is generated in your filesystem but it has not contents since it is not closed. By calling OT.close() the file is closed and its contents are written to the filesystem as shown by the following console output:

# 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

So the last part of your code should be something like:

 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

However, opening and closing a file to write into seems to be kind of annoying. Instead of using .open() and .close() you could use with open(filename, mode) as f as shown below:

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")

This opens the file before doing the stuff below the with open() statement and closes it automatically after the stuff is done.

Upvotes: 1

Related Questions