How to update existing line of file in Python?
Example: I want to update
fix-config = session.xml
fix-config = session-config.xml
The solution @TigerhawkT3 suggested would work great for small/medium files. For extremely large files loading the entire file into memory might not be possible, and then you would want to process each line separately. Something along these lines should work:
import shutil with open('A.txt') as input_file: with open('temp.txt', 'w') as temp_file: for l in input_file: if l.startswith('fix-config'): temp_file.write('fix-config = session-config.xml\n') else: temp_file.write(l) shutil.move('temp.txt', 'A.txt')