Reputation: 159331
Suppose this is my list of languages.
aList = ['Python','C','C++','Java']
How can i write to a file like :
Python : ...
C : ...
C++ : ...
Java : ...
I have used rjust() to achieve this. Without it how can i do ?
Here i have done manually. I want to avoid that,ie; it shuould be ordered automatically.
Upvotes: 2
Views: 153
Reputation: 414215
Automatically determine colon position (using max width) and language order (sorted alphabetically):
languages = ['Python','C','C++','Java']
maxlen = max(map(len, languages))
with open('langs.txt', 'w') as f:
for L in sorted(languages):
f.write('%-*s: ...\n'% (maxlen, L))
print open('langs.txt').read()
Output:
C : ...
C++ : ...
Java : ...
Python: ...
Upvotes: 0
Reputation: 119221
You can do this with string formatting operators
f=open('filename.txt','w')
for item in aList:
print >>f, "%-20s : ..." % item
The 20 is the field width, while the "-" indicates to left justify it.
Upvotes: 5
Reputation: 61529
Do you mean this?
>>> languages = ['Python','C','C++','Java']
>>> f = open('myfile.txt', 'w')
>>> print('\n'.join('%-10s: ...' % l for l in languages), file=f)
>>> f.close()
>>> print(open('myfile.txt').read())
Python : ...
C : ...
C++ : ...
Java : ...
This uses the format specification mini language. Note the print statement uses 3.0 syntax. (Yeah I changed this since Brian's answer links to the 2.5.2 docs. Just for contrast.)
Upvotes: 5