python - formatted output to an external txt file -
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 pattern: firstname lastname age address
i backup.txt has format: lastname firstname address age
how store data in backup.txt in nice formatted way? think should use format() method somehow...
i use print object in code show understood format() far. of course, not desired results.
to answer question: can indeed use .format()
method on string template, see documentation https://docs.python.org/3.5/library/stdtypes.html#str.format
for example:
'the first parameter {}, second parameter {}, third 1 {}'.format("this one", "that one", "there")
will output: 'the first parameter one, second parameter one, third 1 there'
you not seem use format()
in case: 'temp_array[1] {0:20} temp_array[0] {0:20}'.format(temp_array[1], temp_array[0])
output 'temp_array[1] lastname temp_array[0] lastname '
. because {0:20} output 1st parameter format()
, right padded spaces 20 characters.
additionally, there many things improved in code. guess learning python that's normal. here functionally equivalent code produces output want, , makes use of python features , syntax:
with open('data.txt', 'rt') finput, \ open('backup.txt','wt') foutput: line in finput: firstname, lastname, age, address = line.strip().split() foutput.write("{} {} {} {}\n".format(lastname, firstname, address, age)
Comments
Post a Comment