Please tell me what I'm doing wrong.
I have a list, and I want python to make a file out of it.

def changename(filename, modifier):

   return filename[:4]+modifier+filename[-4:]
def fileWrite(filename, ext, sortedList):
   openthis =open(okfilename(changename(filename,'_'+ext)),'wb')
   for item in sortedList:
       openthis.write(item)
       openthis.write('\n')
       return
lastnames.append(newNames)
       lastnames.sort()
   print '\n'.join(lastnames)
   names.close()
   fileWrite(filename, "Last-sorted", lastnames)

Recommended Answers

Look a a little messy,here a couple of way to write a list to a file.
If you need more help post a sample of list and how you want it to look in a file.

l = ['Fauntleroy Duck', 'Mickey Mouse']
with open('names.txt', 'w') as f_out: …
Jump to Post

We are fortunate to have exact and economical documentation in our help files and through internet python.org website plus many additional resources like

Jump to Post

All 5 Replies

Look a a little messy,here a couple of way to write a list to a file.
If you need more help post a sample of list and how you want it to look in a file.

l = ['Fauntleroy Duck', 'Mickey Mouse']
with open('names.txt', 'w') as f_out:
    f_out.write(', '.join(l))

'''Output-->
Fauntleroy Duck, Mickey Mouse
'''
l = ['Fauntleroy Duck', 'Mickey Mouse']
with open('names.txt', 'w') as f_out:
    for line in l:
        f_out.write('%s\n' % line)

'''Output-->
Fauntleroy Duck
Mickey Mouse
'''

So when I do that, the file is suppose to be in my directories? So I can open it? What name would it be under in your example?

When you dont give path to "names.txt" as do in my example.
"names.txt" will be in same directory as you run the script from. open(r'C:\test\names.txt', 'w') here i give a path.
Read a little more in doc as Tony suggest.

thank you for clearing that up :)

Be a part of the DaniWeb community

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