python writing to file is not writing as expected

Viewed 24

Ok so I am trying to write to a file in python I have a for loop to find specific lines in the text file and am then updating the lines within that list however when I write the lines to the new text file they are all being written in one line. Here is my code:

APfile = open(r"C:\X-Plane 11\Aircraft\Perlan2\Perlan2.acf", "r+")

APlist = APfile.readlines()
line_index = []
# iterates through each line of file to find specific string value apends line number to line_index list
for line in APlist:
    if line.find('P acf/_ott_phi_sec_into_future') != -1:
        line_index.append(APlist.index(line)-1)
        # pred_index = APlist.index(line)
    if line.find('P acf/_ott_roll_response') != -1:
        line_index.append(APlist.index(line)-1)
    if line.find('P acf/_ott_phi_deg_off_for_full_def') != -1:
        line_index.append(APlist.index(line)-1)
    if line.find('P acf/_ott_roll_rate') != -1:
        line_index.append(APlist.index(line)-1)
    if line.find('P acf/_ott_phi_sec_to_tune') != -1:
        line_index.append(APlist.index(line)-1)



# takes line index to map function inputs as new autopilot constant values
APlist[line_index[0]]  = "P acf/_ott_phi_sec_into_future" ' ' + roll_pred
APlist[line_index[1]] = "P acf/_ott_roll_response" + ' ' + roll_resp
APlist[line_index[2]] = "P acf/_ott_phi_deg_off_for_full_def" + ' ' + roll_error
APlist[line_index[3]] = "P acf/_ott_roll_rate" + ' ' + roll_rate
APlist[line_index[4]] = "P acf/_ott_phi_sec_to_tune" + ' ' + roll_tunetime
APfile.seek(0)
APfile.writelines(APlist)
APfile.truncate()
#closes file
APfile.close()

expected result:

1 P acf/_ott_phi_sec_into_future

2 P acf/_ott_roll_response
3 P acf/_ott_phi_deg_off_for_full_def

Actual Result:

1 P acf/_ott_phi_sec_into_future P acf/_ott_roll_response P acf/_ott_phi_deg_off_for_full_def
1 Answers

You probably want to add \n to start at a new line.

APfile.write('\n'.join(APlist))

EDIT: And you probably want to delete the contents and then write your list. So you need to swap write and truncate.

APfile.seek(0)
APfile.truncate()
APfile.write('\n'.join(APlist))
Related