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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4