#1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2004
    Posts
    103
    Rep Power
    11

    yet another append question


    greets

    i found this handy function by Netytan to insert strings into a text file.

    Code:
    #Netytan Insert Function
    
    def sappend(file, string, line = 0, out = file):
    	file = open(file, 'r').readlines()
    	file.insert(line, string)
    	open(out, 'w').writelines(file)
    
    sappend('file.txt', 'baby\n', 3, 'new.txt')
    works great,but i have just a few questions.please forgive me if my wording is incorrect.

    1)can i make the string replace the line,not just insert the string into the line?

    2)is there a way i can make the line number a result of raw_input?i am trying to do something like: sappend(fn, string, ln, fn2)

    Code:
    def sappend(file, string, line = 0, out = file):
        
    	file = open(file, 'r').readlines()
    	file.insert(line, string)
    	open(out, 'w').writelines(file)
    
    
    fn= raw_input('file to edit?')
    fn2= raw_input('save name?')
    ln= raw_input('line number?')
    string= raw_input('string to add?')
    
    sappend (fn, string, ln, fn2)
    but i get this error when i use "ln" in the sappend line:
    TypeError: an integer is required

    but "ln" IS a number...can anyone please help?thx in advance
    It is not important if the glass is half full or half empty.What is important,is who has been drinking from MY glass?!?!?
  2. #2
  3. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    because of the nature of the insert method you can't really make it replace the line but you can simply overwrite the value of that line like so...

    Code:
    def rappend(path, string, index = 0, output = path):
    	lines = file(path, 'r').readlines()
    	lines[index] = string
    	file(output, 'w').writelines(lines)
    The reason you're getting an error using raw_input() is because raw_input() always returns a string; even if a number was entered. So u need to type-cast your value using int().

    Code:
    >>> value = raw_input('line number')
    line number10
    >>> value
    '10'
    >>> int(value)
    10
    >>>
    Let me know if you have any questions.

    Mark.
    programming language development: www.netytan.com Hula

  4. #3
  5. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2004
    Posts
    103
    Rep Power
    11
    thank you netytan...rappend works like a charm

    and thank you for explaining how raw_input always returns strings,even if the input is a integer.

    cheers!
    It is not important if the glass is half full or half empty.What is important,is who has been drinking from MY glass?!?!?

IMN logo majestic logo threadwatch logo seochat tools logo