# pcode_io.py  19/01/2016  D.J.Whale

# simplest possible implementation. Only really works well
# for small files.

def readline(filename, lineno):
    f = open(filename)
    lines = f.readlines()
    f.close()
    return lines[lineno-1] # runtime error if does not exist

def writeline(filename, lineno, data):
    # read all lines in
    f = open(filename)
    lines = f.readlines()
    f.close()

    # modify in-memory copy first
    lineno -= 1
    if lineno >= len(lines):
        # pad out extra lines as blanks
        for i in range(1+lineno-len(lines)):
            lines.append("")
    lines[lineno] = data

    # now create a brand new file and write all the lines out
    f = open(filename, "w")
    f.writelines(lines)
    f.close()

# END

@@ -108,16 +108,48 @@
 l files.
+ Poor efficiency on large files.
 %0A%0Adef re
@@ -774,14 +774,916 @@
 lose()%0A%0A
+%0A#----- TEST HARNESS -----------------------------------------------------------%0A%0Adef tests():%0A    pass%0A    # write to a file that does not exist, to create it%0A    # write to a file that does exist, to modify it%0A    # write to a file that is locked, get an error%0A    # write to a file that does not exist, no dir permissions, get error%0A    # write to a file that adds a new line at the end%0A    # write to a file that adds a new line way past the end (padding)%0A    # write to a file that modifies a line to make it longer%0A    # write to a file that modifies a line to make it shorter%0A    %0A    # read from a file that does not exist%0A    # read from a file in a dir with no permissions, get error%0A    # read from a file without read permissions, get error%0A    # read from a file that exists%0A    # read a line that does not exist%0A    # read a line that does exist%0A%0A%0Aif __name__ == %22__main__%22:%0A    tests()%0A%0A
 # END%0A

Test cases specified for io