Python

Snippet list

Edit file

The following functions can be used to edit any provided file. In the selected file a string can be searched that can then be replaced with a given string.

Show/Hide

# search file for string def searchLineWithString(self, string, file): for num, line in enumerate(file, 1): if string in line: return num - 1 # edit line dependend on provided parameter def editLine(self, file, searchString, newLine): selectedFile = open(file, "r") readSelectedFile = selectedFile.readlines() selectedFile.close() # find specific line lineToEdit = searchLineWithString(self, searchString, readSelectedFile) # edit required line readSelectedFile[lineToEdit] = newLine # write lines to files selectedFile = open(file, "w") selectedFile.writelines(readSelectedFile) selectedFile.close()