write whitespace/tab to a text file

D

dirkheld

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()
 
T

Tim Chase

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()

The idiomatic way to do this would be something like

f = open('/path/to/file.txt', 'w')
f.write('\t'.join(names))
f.write('\n')
f.close()

the .join() method on a string joins the contents of a list with
the string on which it's called (in this case, "\t" which is a tab).

-tkc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top