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、入力データが異なっていても変数は残っており、新しいデータは1行下になります。

4

1 に答える 1

3

の間にファイルの位置について何かを想定することは安全ではありませんreadlines()。実装はファイル全体を読み取る場合があり、先読みバッファなどを使用する場合があります。これによりtell、予期しない位置が返されます。

次のことをお勧めします。

  1. ファイルからすべての行を読み取ります(lines = f.readlines()
  2. lines変数を変更します
  3. ファイルを書き直します
于 2012-08-29T07:50:44.347 に答える