Reputation: 8292
I'm trying to work on a function that will change a variable in the script depending on user-input. I started to use the .tell()
built-in to pinpoint the variable to be compared but, the position that it writes to is off by at least 10 bytes?
#! /usr/bin/env python
import re
class file_input:
def __init__(self):
count = 0
change = raw_input('Input? ')
with open('/home/Downloads/FILES/adobe.py','a+') as f:
for line in f.readlines():
if re.findall('script_data', line):
count += 1
## i put in a count to ignore the first 'script_data' mentioned in the __init__ method ##
if change != line[13:] and count == 2:
## if the user-input is not the same, re-write that variable ##
pos = f.tell()
f.seek(pos)
## i checked the position here and its not where i would think it would be ##
print pos
print 'data not matched up, changing now...'
f.write(change)
print line[13:]
f.close()
if __name__ == '__main__':
file_input()
script_data = 'this is going to be some data...'
When I go to check the file though script_data
variable will still be there even if the input data was different and the new data will be a line below.
Upvotes: 0
Views: 691
Reputation: 11557
It is unsafe to assume anything about the file position during readlines()
. The implementation might read the whole file, it might use a read-ahead buffer etc., which cause tell
to return unexpected positions.
I propose you do the following:
lines = f.readlines()
)lines
variableUpvotes: 3