Hi,
It is my code:

mylist = [['fiss','giss'], ['e','h'], ['d','u'], ['c','t'], ['b','o'], ['a','z']]

for alist in mylist:
    g = ' '.join(alist)
print g

f = open("write.txt", "w")
f.write(g)
f.close()

How will I write all the words in the txt file. it is only writing the last line of the file.

Thanks in advance
Regards

Recommended Answers

All 5 Replies

mylist = [['fiss','giss'], ['e','h'], ['d','u'], ['c','t'], ['b','o'], ['a','z']]

g = ''
for alist in mylist:
    g += ' '.join(alist)
print g

f = open("write.txt", "w")
f.write(g)
f.close()

g = '' # It's empty string

in for loop ...
g = something # It's replaced at every time
g += 'sometext' # Saves text in empty variable "g"

There is a lil problem. Now it is writing every words/letter in a single line. It should be like this:

fiss giss
e h
d u
c t
b o
a z

Regards

Look at the output -ordi-
fiss gisse hd uc tb oa z
Do you see some character are missing?

I dont know how BirdaoGwra want the output,here are a couple of way.
fissgiss is one word in this,some more work is neede to split that to.
Pickle is way to save and get same output back,look at this.
http://www.daniweb.com/forums/thread343685.html

l = [['fiss','giss'], ['e','h'], ['d','u'], ['c','t'], ['b','o'], ['a','z']]

with open('w.txt', 'w') as f:
    f.writelines(''.join(i) + ' ' for i in l)
#--> fissgiss eh du ct bo az 

#---------------------------------------#
l = [['fiss','giss'], ['e','h'], ['d','u'], ['c','t'], ['b','o'], ['a','z']]

with open('w.txt', 'w') as f:
    f.writelines(''.join(i) + '\n' for i in l)

"""Output-->
fissgiss
eh
du
ct
bo
az
"""

Edit did see you post about output.

l = [['fiss','giss'], ['e','h'], ['d','u'], ['c','t'], ['b','o'], ['a','z']]

with open('w.txt', 'w') as f:
    f.writelines(' '.join(i) + '\n' for i in l)

"""Output-->
fiss giss
e h
d u
c t
b o
a z
"""
commented: I learned from him. +2

@snippsat:
Thank you very much.

Regards

Not sure which editor you use, but, with PyScripter (Free), you can run to where the cursor is sitting in your code, then step (F8) line by line and watch the value of your variables change. This is a HUGE help when you're trying to pin down what's going on in loops. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.