whatsherface
whatsherface

Reputation: 413

Why is this writing part of the text to a new line? (Python)

I'm adding some new bits to one of the lines in a text file and then writing it along with the rest of the lines in the file to a new file. Referring to the 2nd if statement in the while loop, I want that to be all on the same line:

path = raw_input("Enter the name of the destination folder: ")

source_file = open("parameters")
lnum=1
for line in source_file:
    nums = line.split()
    if (lnum==10):
        mTot = float(nums[0])
    if (lnum==11):
        qinit = float(nums[0])
    if (lnum==12):
        qfinal = float(nums[0])
    if (lnum==13):
        qgrowth = float(nums[0])
    if (lnum==14):
        K = float(nums[0])
    lnum = lnum+1

q = qinit
m1 = mTot/(1+qinit)
m2 = (mTot*qinit)/(1+qinit)
taua = (1/3.7)*(mTot**(-4.0/3.0))
taue = taua/K
i = 1
infname = 'parameters'
while (q <= qfinal):
    outfname = path+'/'+str(i)
    oldfile = open(infname)
    lnum=1
    for line in oldfile:
        if (lnum==17):
            line = "{0:.2e}".format(m1)+' '+line
        if (lnum==18):
            line = "{0:.2e}".format(m2)+' '+line+' '+"{0:.2e}".format(taua)+' '+"      {0:.2e}".format(taue)
        newfile = open(outfname,'a')
        newfile.write(line)
        lnum=lnum+1
    oldfile.close()
    newfile.close()
    i=i+1
    q = q + q*(qgrowth)
    m1 = mTot/(1+q)
    m2 = (mTot*q)/(1+q)

but taua and taue are being written on the line below the rest of it. What am I missing here?

Upvotes: 0

Views: 91

Answers (2)

Levon
Levon

Reputation: 143022

That is because line still contains the trailing newline, and when you concatenate it you are also including the newline.

Insert a

line = line.strip()

right after the if (lnum == 19): but before you put the longer line together to get rid of the newline.

Note that write will not add a newline automatically, so you'll want to add a trailing newline of your own.

UPDATE:

This is untested, but I think unless I messed up, you could just use this instead of your longer line:

 line = line.strip()
 line = "{0:.2e} {} {0:.2e}   {0:.2e}\n".format(x, line, y, z)

Upvotes: 4

alanmanderson
alanmanderson

Reputation: 8200

If you use line = rstrip(line) on line before you change the line then it will trim the new line (as well as any whitespace).

Upvotes: 0

Related Questions