Skip to content Skip to sidebar Skip to footer

Error In Writing A Text File In Python

I am writing a text file with the following code(pl in the code is a list of lists): out_file = open('par.txt', 'w') out_file.write('id\ttrans_id\ttype\tstatus\tname\ttrans_type\tt

Solution 1:

You need to change the loop to something like:

for lst in pl:
    out_file.write('\t'.join(x.split()(1) for x in lst))
    out_file.write('\n')

Solution 2:

Try this:

with open("par.txt", "a+") as f:
    f.write("id\ttrans_id\ttype\tstatus\tname\ttrans_type\ttrans_status\ttrans_name\n")
    for lst in pl:
        f.write(("{}\t"*8).format(lst[0].split()[1],lst[1].split()[1],lst[2].split()[1],lst[3].split()[1],lst[4].split()[1],lst[5].split()[1],lst[6].split()[1],lst[7].split()[1]))

It's not going to overwrite your file.You should change that 8 variable what is the length of your list, which is we dont know that list.

Example Output:

enter image description here


Post a Comment for "Error In Writing A Text File In Python"