0
fp = open ('data.txt','r')
saveto = open('backup.txt','w')
someline = fp.readline()
savemodfile = ''
while someline :
    temp_array = someline.split()
    print('temp_array[1] {0:20} temp_array[0] {0:20}'.format(temp_array[1], temp_array[0]), '\trating:', temp_array[len(temp_array)-1]))
    someline = fp.readline()
    savemodfile =  temp_array[1] + '  ' + temp_array[0] +',\t\trating:'+ temp_array[10]
    saveto.write(savemodfile + '\n')
fp.close()
saveto.close()

The input file :data.txt has records of this pattern: firstname Lastname age address

I would like the backup.txt to has this format: Lastname firstname address age

How do i store the data in the backup.txt in a nice formatted way? I think i should use format() method somehow...

I use the print object in the code to show you what i understood about format() so far. Of course, i do not get the desired results.

scf
  • 396
  • 2
  • 19
Mynicks
  • 213
  • 1
  • 9
  • 1
    Just what do you mean by "a nice formatted way"? You could have each field take a predetermined number of characters, but that has the disadvantage that longer values may not fit. You could separate fields with commas, spaces, or quotes, but that prevents those characters from being in the fields. We can't help you unless you give more details on the data and on what you want. – Rory Daulton Nov 08 '16 at 11:19

3 Answers3

0

To answer your question: you can indeed use the .format() method on a string template, see the documentation https://docs.python.org/3.5/library/stdtypes.html#str.format

For example:

'the first parameter is {}, the second parameter is {}, the third one is {}'.format("this one", "that one", "there")

Will output: 'the first parameter is this one, the second parameter is that one, the third one is there'

You do not seem to use format() properly in your case: 'temp_array[1] {0:20} temp_array[0] {0:20}'.format(temp_array[1], temp_array[0]) will output something like 'temp_array[1] Lastname temp_array[0] Lastname '. That is because {0:20} will output the 1st parameter to format(), right padded with spaces to 20 characters.

Additionally, there is many things to be improved in your code. I guess you are learning Python so that's normal. Here is a functionally equivalent code that produces the output you want, and makes good use of Python features and syntax:

with open('data.txt', 'rt') as finput, \
     open('backup.txt','wt') as foutput:
    for line in finput:
        firstname, lastname, age, address = line.strip().split()
        foutput.write("{} {} {} {}\n".format(lastname, firstname, address, age)
Guillaume
  • 5,497
  • 3
  • 24
  • 42
  • Split and strip both remove whitespaces(because they have no arguments).can you explain why you do not use only split or only strip? I do not understand what the strip.split wants to 'catch'. – Mynicks Nov 08 '16 at 14:45
  • `strip()` will remove unnecessary whitespaces at the beginning and/or the end of the line. If there is no such spaces, then it returns the same string. It does not change any spaces _inside_ the string. `split()` will cut the string into pieces using space as the delimiter and return a list of resulting strings. `strip()` might not be necessary in your case, but it doesn't hurt :) – Guillaume Nov 08 '16 at 14:51
  • Also, how do i close these two files properly? finput.close() and foutput.close() throw SyntaxError – Mynicks Nov 08 '16 at 15:02
  • But I said it is functionally equivalent ;) Both files are closed properly automatically when the `with` block ends. See for example https://stackoverflow.com/questions/3012488/what-is-the-python-with-statement-designed-for?rq=1 for an explanation, or http://preshing.com/20110920/the-python-with-statement-by-example/ – Guillaume Nov 08 '16 at 15:18
  • Thanks. Takes months to get a good grasp of the language and the official website is written in a succinct <>. – Mynicks Nov 08 '16 at 15:40
0

This code will give you a formatted output on the screen and in the output file

fp = open ('data.txt','r')
saveto = open('backup.txt','w')
someline = fp.readline()
savemodfile = ''
while someline :
    temp_array = someline.split()
    str = '{:20}{:20}{:20}{:20}'.format(temp_array[1], temp_array[0], temp_array[2], temp_array[3])
    print(str)    
    savemodfile =  str
    saveto.write(savemodfile + '\n')
    someline = fp.readline()    

fp.close()
saveto.close()

But this is not a very nice code in working with files, try using the following pattern:

with open('a', 'w') as a, open('b', 'w') as b:
    do_something()

refer to : How can I open multiple files using "with open" in Python?

Community
  • 1
  • 1
Serjik
  • 10,543
  • 8
  • 61
  • 70
0
fp = open ('data.txt','r')
saveto = open('backup.txt','w')
someline = fp.readline()
savemodfile = ''
while someline :
    temp_array = someline.split()
    someline = fp.readline()
    savemodfile = '{:^20} {:^20} {:^20} {:^20}'.format(temp_array[1],temp_array[0],temp_array[3],temp_array[2])
    saveto.write(savemodfile + '\n')
fp.close()
saveto.close()
SuFi
  • 355
  • 1
  • 3
  • 17