[Tutor] Stumped Again

Brian Jones bkjones at gmail.com
Sun Oct 31 02:08:59 CET 2010


On Sat, Oct 30, 2010 at 7:12 PM, Terry Green <tmantjg at yahoo.com> wrote:

>  *Am running this Script and cannot figure out how to close my files,*
>
> *Keep getting msg: Attribute Error: ‘_csv.writer’ object has no attribute
> ‘close’*
>
> *Why?*
>

Because csv.writer objects don't have a close() method. Files do :)


> testOutput =
> csv.writer(open('c:/users/terry/downloads/tup1012k/tup1012.csv', 'w'),
>

See this line? testOutput is a csv.writer object, which you pass a file to.
How about creating a file handle first, and passing that in, like this:

testOutputFile = open('c:/users/terry/downloads/whatever.csv', 'w')
testOutputCSV = csv.writer(testOutputFile)
<....do stuff...>
testOutputFile.close()

You can also use the 'with' statement:

with open('c:/users/terry/whatever.csv', 'w') as myfile:
    testOutputCSV = csv.writer(myfile)
    <....do stuff...>

The 'with' statement is used with ContextManager objects, and files
implement the ContextManager protocol which (among other things) means that
the file will be closed in the above snippet without you having to
explicitly call close() on it.

hth.
brian




> delimiter=',',
>
>                          quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
>
> csvreader =
> csv.reader(open("c:/users/terry/downloads/tup1012k/tup1012x.drf","r"),delimiter=',')
>
> for row in csvreader:
>
>     test=('test4')
>
>     track=row[0]
>
>     rdate=row[1]
>
>     race=row[2]
>
>     postPos=row[3]
>
>     entry=row[4]
>
>     distance=row[5]
>
>     surface=row[6]
>
>     Reserved=row[7]
>
>     raceType=row[8]
>
>     ageSex=row[9]
>
>     todaysRaceClassification=row[10]
>
>     purse=row[11]
>
>     claimingPrice=row[12]
>
>     jockey=row[32]
>
>     jockeySts = int(row[34])
>
>     jockeyWins = int(row[35])
>
>     horseName=row[44]
>
>     daysSinceLR=row[223]
>
>     try:
>
>             jockeyPct=round((jockeyWins/jockeySts)*100)
>
>     except ZeroDivisionError:
>
>             print
> (track,race,postPos,horseName,jockey,jockeyWins,jockeySts,0)
>
>     else:
>
>         print
> (track,race,postPos,horseName,jockey,jockeyWins,jockeySts,jockeyPct)
>
>
> testOutput.writerow((track,race,postPos,horseName,jockey,jockeyWins,jockeySts,jockeyPct,'\n'))
>
> testOutput.close()
>
> csvreader.close()
>
>
>
> Please Help!!!!!
>
>
>
> Terry Green
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Brian K. Jones
My Blog          http://www.protocolostomy.com
Follow me      http://twitter.com/bkjones
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20101030/bb1b3cc3/attachment-0001.html>


More information about the Tutor mailing list