[Tutor] Create file / Print list to file

Kent Johnson kent_johnson at skillsoft.com
Wed Aug 11 20:20:28 CEST 2004


Klas,

You can create a file by opening it for writing.

Note that file.write() doesn't append a newline, so you may have to write 
them yourself depending on what is in your list and what you want the 
output to look like.

Here is an example that formats the lines with spaces between the list 
items. Danny gave you an example that writes the literal list.

Kent

 >>> l=[ ['line', 'one'], ['second', 'line'], ['this', 'is', 'the', 'third'] ]
 >>> f=open('foo.txt', 'w')
 >>> for line in l:
...   lineData = ' '.join(line)
...   f.write(lineData)
...   f.write('\n')
...
 >>> f.close()
 >>> f=open('foo.txt')
 >>> for line in f:
...   print line,
...
line one
second line
this is the third
 >>>

Kent


At 07:58 PM 8/11/2004 +0200, you wrote:
>Hi and thanks for all the previous answers. I am still struggling with my
>conversion program.
>
>Here are todays questions :)
>
>1. Is it possible to tell python to create a file (for example if specified
>file doesnt exist)? It sems possible to create a directory thrue the os
>module. But i cant find out how to create a file.
>
>2. How can i print a list to a file? I have tried the following:
>
>def writeListToFile(inputList, outputFile):
>     a = open(outputFile, "w")
>     listLength = len(inputList)
>     for i in range(0,listLength):
>         a.write(inputList[i])
>     a.close()
>
>but i get a "Type error"
>
>inputList is list of lists (each row is list)
>
>Klas
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list