Python 02 – file basics

To open and read a file in Python is fairly easy:

f = open('/Users/jem/Desktop/python/numberlines.py')
line = f.readline()
while line != "":
    print line
    line = f.readline()
f.close()

Resulting in

import sys

if len(sys.argv) < 2:
    print "Not enough arguments"
else:
    myfile = sys.argv[1]
    f = open( myfile )
    counter = 1
    currentline = f.readline()
    while currentline != "":
        print "%4d : %s " % (counter, currentline[:-1])
        currentline = f.readline()
        counter = counter + 1
    f.close()

It's also possible to read all the lines and store them in a list:

f = open('/Users/jem/Desktop/python/numberlines.py')
lines = f.readlines()
f.close()
print lines
['import sys\n', '\n', 'if len(sys.argv) < 2:\n', '\tprint "Not enough arguments"\n', 'else:\n', '\tmyfile = sys.argv[1]\n', '\tf = open( myfile )\n', '\tcounter = 1\n', '\tcurrentline = f.readline()\n', '\twhile currentline != "":\n', '\t\tprint "%4d : %s " % (counter, currentline[:-1])\n', '\t\tcurrentline = f.readline()\n', '\t\tcounter = counter + 1\n', '\tf.close()']

If you want to create a file and write to it:

f = open('/Users/jem/Desktop/python/output.txt','w')
f.write('Hello world')
f.write(' this is on the same line\n')
f.write('This is some text\nto show you\nsome text')
f.close()

which creates a file

output.txt

with the following content

Hello world this is on the same line
This is some text
to show you
some text

If you’re writing some code for doing file manipulations you probably want to check out the

<a href="http://docs.python.org/lib/module-os.path.html">os.path</a>

library module. For example to check if a file exists:

import os.path

if os.path.exists('/Users/jem/Desktop/python/output.txt'):
    print "The file exists"
else:
    print "The file doesn't exist"

The

<a href="http://docs.python.org/lib/module-os.path.html">os.path</a>

module contains several useful functions for manipulating file paths. For example to join parts of a file path:

import os.path

print os.path.join('/var/log','somefile.log')
print os.path.join('/var/log','subfolder','subsubfolder','file.log')
/var/log/somefile.log
/var/log/subfolder/subsubfolder/file.log

Note that these function always handle paths correctly, that is correctly use ‘/’, ‘\’, etc, depending on file system. Perhaps even more useful are the functions to divide a file path into different parts:

res = os.path.split(examplepath)

print 'part1',res[0]
print 'part2',res[1]

res = os.path.splitext(examplepath)
print 'part1', res[0]
print 'part2', res[1]
part1 /home/jem/doc
part2 sample.markdown
part1 /home/jem/doc/sample
part2 .markdown
blog comments powered by Disqus