write whitespace/tab to a text file

Sébastien Weber valereG at hotmail.fr
Fri Oct 19 17:06:55 CEST 2007


Le Fri, 19 Oct 2007 07:33:29 -0700, dirkheld a écrit :

> Hi,
> 
> I would l like to write some data to a text file. I want to write the
> data with whitespace or tabs in between so that I create tabular columns
> like in a spreadsheet. How can I do this in python. (btw, I'm new to
> python)
> 
> names = ['John','Steve','asimov','fred','jim'] ## output I would like in
> txt file : John         Steve asimov      fred     jim
> 
> f=open('/User/home/Documents/programming/python/test.txt','w')
> 	for x in range(len(names)):
> 		f.write(tags[x])
> 	f.close()
Maybe :

names = ["Sebastien", "Ana", "Elodie", "Mohamed", "Antoniavna"]
maxlen = max(len(n) for n in names)
linetowrite = ""
for n in names:
    linetowrite += n.ljust(maxlen + 3, ' ')
f = open('test.txt', 'w')
f.writelines(linetowrite.strip(' ') + '\n')
f.close()



More information about the Python-list mailing list