简体   繁体   中英

formatting output file using python

I am trying to format my output file with the following data. Country (50 characters) Income Level (6 characters) Percent Vaccinated (3 characters) Region (25 characters) Year (4 characters) Here is my code:

f1=input('file name: ')

output_file=open(f1,'w')
for line in input_file:
    newstring=''
    line=line.strip()
    for ch in line:
        print('{0:<50s}{1:<6s}{2:<3s}{3:<25s}{4:<4s}'.format(line[0:50],line[50:56],line[56:59],line[59:84],line[84:87],file=output_file)   

input_file.close()
output_file.close()

Here is what I am getting as error:

file name: output_file.txt
Traceback (most recent call last):
  File "C:/Users/Dasinator/Documents/Books IX/Python Examples/proj07.py", line 10, in <module>
    print('{0:<50s}{1:<6s}{2:<3s}{3:<25s}{4:<4s}'.format(line[0:50],line[50:56]),line[56:59],line[59:84],line[84:87],file=output_file)
IndexError: tuple index out of range

I have been working on this thing for quite some time now and just don't know where I am going wrong. Could anyone please write where the problem lies? Thanks

You have added a ) after the second argument in the format function. Then you continue to add arguments, which python is considering part of the print function, which doesn't take so many arguments.

Along with this, the format function is now expecting 6 arguments but you only supplied 2, hence the error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM