error in writing a text file in python [closed]

2019-09-11 08:42发布

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\ttrans_status\ttrans_name\n")
for lst in pl:
    out_file(lst[0].split()[1],"\t",lst[1].split()[1],"\t",lst[2].split()[1],"\t",lst[3].split()[1],"\t",lst[4].split()[1],"\t",lst[5].split()[1],"\t",lst[6].split()[1],"\t",lst[7].split()[1])
out_file.close()

BUT it gives this error:

Traceback (most recent call last):
  File "test.py", line 25, in <module>
    out_file(lst[0].split()[1],"\t",lst[1].split()[1],"\t",lst[2].split()[1],"\t",lst[3].split()[1],"\t",lst[4].split()[1],"\t",lst[5].split()[1],"\t",lst[6].split()[1],"\t",lst[7].split()[1])
TypeError: 'file' object is not callable

标签: python file
2条回答
ゆ 、 Hurt°
2楼-- · 2019-09-11 09:08

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

查看更多
Fickle 薄情
3楼-- · 2019-09-11 09:24

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')
查看更多
登录 后发表回答