[Tutor] Create file / Print list to file
Nick Lunt
nick at javacat.f2s.com
Wed Aug 11 20:22:49 CEST 2004
Hi Klas,
>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.
lets say you dont have a file called '/newfile'.
>>> f = open('/anyfile','w')
>>> f.close()
You do now ;) There may be an easier way, but that seems easy enough to me.
> 2. How can i print a list to a file? I have tried the following:
Your correct in that you cant write a list to a file, but you seem to be
iterating through your list in a strange way, this is simpler
>>> l = ['this','is','a','list']
>>> f = open('/anyfile','w')
>>> for i in l:
... f.write(i)
>>> f.close()
if you look at the contents of /anyfile it will contain the contents of list
l.
Hope that helps
Nick.
-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On
Behalf Of Klas Marteleur
Sent: 11 August 2004 18:58
To: tutor at python.org
Subject: [Tutor] Create file / Print list to file
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