1To solve the above error Try This:
2 with open('file.txt','r+') as f:
3 # Try to seek the position to 0
4 f.seek(0)
5 f.truncate(0)
6for me it solved the problem
7
8OR
9import fileinput
10
11for line in fileinput.input('file.txt', inplace=1):
12 pass