[Tutor] Create file / Print list to file
kent_johnson at skillsoft.com
Wed Aug 11 20:20:28 CEST 2004
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.
>>> l=[ ['line', 'one'], ['second', 'line'], ['this', 'is', 'the', 'third'] ]
>>> f=open('foo.txt', 'w')
>>> for line in l:
... lineData = ' '.join(line)
>>> for line in f:
... print line,
this is the third
At 07:58 PM 8/11/2004 +0200, you wrote:
>Hi and thanks for all the previous answers. I am still struggling with my
>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):
>but i get a "Type error"
>inputList is list of lists (each row is list)
>Tutor maillist - Tutor at python.org
More information about the Tutor