user3260982
user3260982

Reputation:

how to format output file in python?

I am trying to format my output file exactly like my input file. I was wondering if anyone could give me some pointers. My codes are:

input_file=open('abcd.txt','r')

f1=input('file name: ')

output_file=open(f1,'w')
for line in input_file:
    output_file.write(line)

input_file.close()
output_file.close()

My input file looks like the following. Where country is 50 chars long, second category is 6 chars, third is 3 chars, fourt is 25 chars, and year is 4 chars long. The following is the inputfile.

Afghanistan                                        WB_LI   68 Eastern Mediterranean     2012
Albania                                            WB_LMI  90 Europe                      1980
Albania                                            WB_LMI  90 Europe                    1981

The following is how my output file looks like:

Afghanistan                                        WB_LI   68 Eastern Mediterranean     2012
Albania                                           WB_LMI  90 Europe                    1980
Albania                                           WB_LMI  90 Europe                    1981

Upvotes: 0

Views: 9653

Answers (1)

Maciej Gol
Maciej Gol

Reputation: 15854

Use string formatting, mainly {:-x} where x denotes the minimal length of the string (filled with whitespace) and - denotes to left-align the contents:

output_file.write('{:-50} {:-6} {:-3} {:-25} {:-4}\n'.format(country, category, third, fourth, year)) 

Upvotes: 2

Related Questions