python .tell()给文件中意想不到的位置?
问题描述:
我正在尝试根据用户输入来改变脚本中的变量。我开始使用内置的.tell()
来精确定位要比较的变量,但是它写入的位置至少关闭了10个字节?python .tell()给文件中意想不到的位置?
#! /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...'
当我去检查文件虽然script_data
变量仍然会在那里,即使输入的数据是不同的,新的数据将低于线。
答
它是不安全的过程中readlines()
承担有关文件位置的任何。该实现可能会读取整个文件,它可能会使用预读缓冲区等,这会导致tell
返回意外位置。
我建议你做到以下几点:
- 从文件中读取所有的行(
lines = f.readlines()
) - 变化
lines
变量 - 重新写入文件
你提出什么,我认为会是一个更好的解决方案:) readlines()是问题出在哪里,你是对的。谢谢! – tijko