0

我正在尝试开发一个函数,该函数将根据用户输入更改脚本中的变量。我开始使用.tell()内置来确定要比较的变量,但是它写入的位置至少偏移了 10 个字节?

#! /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时,即使输入数据不同,变量仍然存在,并且新数据将在下面一行。

4

1 回答 1

3

readlines(). 该实现可能会读取整个文件,它可能会使用预读缓冲区等,这会导致tell返回意外的位置。

我建议您执行以下操作:

  1. 从文件中读取所有行 ( lines = f.readlines())
  2. 改变lines变量
  3. 重写文件
于 2012-08-29T07:50:44.347 回答