0

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
6
  • You are writing each line from input_file to f1 exactly as read. What exactly is the problem? Commented Feb 22, 2014 at 18:37
  • Yes, sorry. I was copying and pasting from a bigger file and forgot to change the variable. Commented Feb 22, 2014 at 18:37
  • 1
    If you're getting all your output in one line, maybe you should try adding a line break ("\n") after each line you print. Commented Feb 22, 2014 at 18:38
  • What exactly is your problem, it looks like input and output are identical and that is what you want, isn't it? Please provide more details on the issue Commented Feb 22, 2014 at 18:53
  • For some reason, when I am pasting my output file and input file in here, they are looking identical. But, on my computer screen, they are not looking like they are identically aligned. Commented Feb 22, 2014 at 19:01

1 Answer 1

2

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)) 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.