python - How to open a file and change a line -
i've looked @ loads of threads on cant find right answer:
i'm bit new python. im opening file in python, inserting 1 line before beginning line , 1 before last line , reconstructing lines string variable @ end.
heres function im trying run on opened file. changes lines mode="0" mode="1" or vice versa.
def modes(file, mode): endstring = '' if(mode == 1): mode0 = 'mode="0"' mode1 = 'mode="1"' else: mode0 = 'mode="1"' mode1 = 'mode="0"' line in iter(file): if 'modes' in line: line = line.replace(mode0,mode1) endstring += line return endstring
so try following:
mode = 1 input_file = open("c:\myfile.txt") input_file.readlines() lengthlines = len(input_file) #insert line @ position 1 input_file.insert(1,'<variable name="init1" />') #insert line @ last line position - 1 input_file.insert(lengthlines,'<variable name="init2" />') #join lines again input_file = "".join(input_file) #run modes function - replace occurrences of mode=x finalfile = modes(input_file,mode) print finalfile
and im getting error, "object of type file, has no "len()"" , general object/list errors.
it seems im getting objects/lists etc mixed im not sure - grateful assistance - cheers
input_file.readlines()
returns content not assign input_file. you'll have assign return value of call variable, so:
file_content = input_file.readlines()
and pass len()
lengthlines = len(file_content)
edit: solving issue len() leads further exceptions. should want:
mode = 1 open("c:\myfile.txt") input_file: file_content = list(input_file.readlines()) file_content.insert(0,'<variable name="init1" />') file_content.append('<variable name="init2" />') finalfile = modes(file_content,mode) print finalfile
you might have alter string concatenation in function if want stick several lines.
endstring += line + '\n' return endstring.rstrip('\n')
this not yet write new content file though.
edit2: , practice close file when done it, therefore updated above use context manager takes care of this. explicitly call input_file.close()
after finished.
Comments
Post a Comment