insert line in middle of file

Bob Kline bkline at rksystems.com
Mon Apr 2 14:15:04 EDT 2001


On 2 Apr 2001, Holland King wrote:

> i have a file that must have some stuff at the beginning and the end
> and i need to add a line to the middle. is there any easy way to do
> this without losing data? thank you.

Something along these lines, perhaps?  Last argument specifies the
number of lines from the end where the new line should be inserted.

#----------------------------------------------------------------------
# Pull in required modules.
#----------------------------------------------------------------------
import sys, string

#----------------------------------------------------------------------
# Extract command-line arguments.
#----------------------------------------------------------------------
fileName = len(sys.argv) > 1 and sys.argv[1] or 'test.txt'
newLine  = len(sys.argv) > 2 and sys.argv[2] or 'Some new data'
position = len(sys.argv) > 3 and string.atoi(sys.argv[3]) or 2

#----------------------------------------------------------------------
# Read the file.
#----------------------------------------------------------------------
file  = open(fileName, 'r')
lines = file.readlines()
file.close()

#----------------------------------------------------------------------
# Insert the new line.
#----------------------------------------------------------------------
if position <= len(lines):
    lines[-position:-position] = [newLine + "\n"]

#----------------------------------------------------------------------
# Write the file back out.
#----------------------------------------------------------------------
file = open(fileName, 'w')
file.writelines(lines)
file.close()

-- 
Bob Kline
mailto:bkline at rksystems.com
http://www.rksystems.com





More information about the Python-list mailing list