Writing to a file

eryksun () eryksun at gmail.com
Fri Mar 25 21:11:23 EDT 2011


On Friday, March 25, 2011 11:07:19 AM UTC-4, jyou... at kc.rr.com wrote:
>
> >>> f = open('~/Desktop/test.txt', 'w')
> >>> f.write('testing 1... 2... 3...')
> >>> f.close()

Consider using "with" to automatically close the file and os.path for cross-platform compatibility:

    import os.path
    user_home = os.path.expanduser('~')
    test_absname = os.path.join(user_home, 'Desktop', 'test.txt')
    
    with open(test_absname, 'w') as test:
        test.write('testing 1... 2... 3...')




More information about the Python-list mailing list