|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
||||
|
||||
|
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
|
||||
|
||||
|
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. |
|
#3
|
||||
|
||||
|
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! |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > yet another append question |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|