![]() If match_string in contents: # Handle last line to prevent Inde圎rror ![]() In our particular application, we wanted to add it after a certain string: with open(file, 'r+') as fd: ![]() There is a combination of techniques which I found useful in solving this issue: with open(file, 'r+') as fd:Ĭontents.insert(index, new_string) # new_string should end in a newlineįd.seek(0) # readlines consumes the iterator, so we need to start overįd.writelines(contents) # No need to truncate as we are increasing filesize If you want to search a file for a substring and add a new text to the next line, one of the elegant ways to do it is the following: import fileinputįor line in fileinput.FileInput(file_path,inplace=1): "index" and "value" are the line and value of your choice, lines starting from 0.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |