0

Is it possible to use try to achieve that either creating a new file with a header or appending if the file exists.

Secondly, could I add two statements under except clause.

Hname = os.uname()[1].split(".")[0]
Cdate = datetime.now().strftime("%Y%m%d")
# .....
MPSTAT = '/home/mongod/monitor/rpt/'+Hname+'/mpstat.'+Cdate


try:
    f_mpstat = open(MPSTAT,'r')
except FileNotFoundError:
    f_mpstat = open(MPSTAT,'w')
    f_mpstat.write("Start time => {0}    interval => {1:4d}    count => {2:4d} \n".format(Ctime, Interval, Count))

f_mpstat = open(MPSTAT,'a')
the_storyteller
  • 2,335
  • 1
  • 26
  • 37
moon monk
  • 1
  • 3
  • It looks like you just did both of the things you are asking if they were possible. Does it work? If so, what is your question? If not, could you be more specific about what the problem is? – mkrieger1 Nov 15 '17 at 17:11
  • I think opening the file in "a+" mode would help you out. Related answer: https://stackoverflow.com/questions/13248020/whats-the-difference-between-r-and-a-when-open-file-in-python – Quentin Nov 15 '17 at 17:11
  • My original statement has two problems. – moon monk Nov 15 '17 at 17:54
  • My original statement has two problems. First, " f_mpstat = open(MPSTAT,'r') " is only allowed to read not to "append". Therefore, I have to close file header and open with open(MPSTAT,'a') outside of Try statement. Second problem, the second line "f_mpstat.write("Start time => {0} ...." under except clause is never write " Start time =>..... " into the new file. the new file is created if the file does not exist. Thank you. – moon monk Nov 15 '17 at 18:02
  • I find the answer of my second question, I have not issued f_mpstat.close() and the header is still in cache not write to the new file. after i run "f_mpstat.close()", i saw the file in filesystem. For MY first question, " f_mpstat = open(MPSTAT,'r') " is only allowed to read not to "append". Therefore, I have to close file header and open with open(MPSTAT,'a') outside of Try statement. >> I tried use 'a' as the second argument in "open" clause, but it breaks the logic. I want the script look neat and short. – moon monk Nov 15 '17 at 18:41

0 Answers0