Reputation:
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('measles.txt','r')
f1=input('file name: ')
output_file=open(f1,'w')
for line in input_file:
newstring=''
line=line.strip()
for ch in line:
newstring+=ch
print(newstring,file=output_file)
input_file.close()
output_file.close()
The input file looks like this:
Afghanistan WB_LI 65 Eastern Mediterranean 2011
Afghanistan WB_LI 68 Eastern Mediterranean 2012
Albania WB_LMI 90 Europe 1980
Albania WB_LMI 90 Europe 1981
and my output file is looking like this:
Afghanistan WB_LI 65 Eastern Mediterranean 2011
Afghanistan WB_LI 68 Eastern Mediterranean 2012
Albania WB_LMI 90 Europe 1980
Albania WB_LMI 90 Europe 1981
It is not aligned properly.
Upvotes: 0
Views: 293
Reputation: 9275
This answer response to your question: How to print a list tuples in a nice format?
Use of Python string format: http://docs.python.org/2/library/string.html#format-examples
Upvotes: 0
Reputation: 297
It looks like the field width is the problem. Try using padding: http://docs.python.org/release/3.0.1/whatsnew/2.6.html#pep-3101
Here's my example for your input:
strings = []
fmt = '{0:30} {1:8} {2:4} {3:30} {4:8}'
strings.append(fmt.format("Afghanistan", "WB_LI", 65, "Eastern Mediterranean", 2011))
strings.append(fmt.format("Afghanistan", "WB_LI", 68, "Eastern Mediterranean", 2012))
strings.append(fmt.format("Albania", "WB_LMI", 90, "Europe", 1980))
strings.append(fmt.format("Albania", "WB_LMI", 90, "Europe", 1981))
for str in strings:
print(str)
Output:
Afghanistan WB_LI 65 Eastern Mediterranean 2011
Afghanistan WB_LI 68 Eastern Mediterranean 2012
Albania WB_LMI 90 Europe 1980
Albania WB_LMI 90 Europe 1981
Upvotes: 0
Reputation: 1394
You could do:
input_file=open('measles.txt','r')
f1 = 'out.txt'
output_file=open(f1,'w')
for line in input_file:
line=line.rstrip()
print(line)
input_file.close()
output_file.close()
But I guess you actually want to modify something in the line before you print it. If you tell me what, I will try and help you.
Upvotes: 1