1

他の行に影響を与えることなく、テキスト ファイル内のいくつかの行を変更しようとしています。これが「text.txt」というテキストファイルの中身です

this is  a test1|number1
this is a test2|number2
this is a test3|number2
this is a test4|number3
this is a test5|number3
this is a test6|number4
this is a test7|number5
this is a test8|number5
this is a test9|number5
this is a test10|number5

私の目的は、4 行目と 5 行目を変更し、残りは同じままにすることです。

mylist1=[]
for lines in open('test','r'):
    a=lines.split('|')
    b=a[1].strip()
    if b== 'number3':
        mylist1.append('{}|{} \n'.format('this is replacement','number7'))
    else:
         mylist1.append('{}|{} \n'.format(a[0],a[1].strip()))
myfile=open('test','w')
myfile.writelines(mylist1)

コードは機能しますが、それを行うためのより良い効率的な方法があるかどうか疑問に思っていますか? 行番号だけでファイルを読み取ることはできますか?

4

5 に答える 5

3
import fileinput

for lines in fileinput.input('test', inplace=True):
    # inplace=True redirects stdout to a temp file which will
    # be renamed to the original when we reach the end of the file. this
    # is more efficient because it doesn't save the whole file into memeory
    a = lines.split('|')
    b = a[1].strip()
    if b == 'number3':
        print '{}|{} '.format('this is replacement', 'number7')
    else:
        print '{}|{} '.format(a[0], a[1].strip())
于 2013-05-17T08:46:33.360 に答える
0

あなたの意図が、置き換えられる行をそので識別することなのか、それとも行番号によって識別することなのかは完全には明らかではありません。

前者が目的の場合は、次のような行のリストを取得できます。

with open('test','r') as f:
    oldlines = f.read().splitlines()

空白が続く危険性がある場合は、次のこともできます。

次に、次のように処理できます。

newlines = [ line if not line.strip().endswith('|number3') else 'this is replacement|number7' for line in oldlines]

宛先ファイルを開き (ここでは元のファイルを上書きすることを想定しています)、すべての行を書き込みます。

with open('test','w') as f:
    f.write("\n".join(newlines))

これは、あらゆる種類の単純な行フィルタリングに役立つ一般的なパターンです。

行を番号で識別したい場合は、「改行」行を変更するだけです。

 newlines = [ line if i not in (3, 4) else 'this is replacement|number7' for i, line in enumerate(oldlines)]
于 2013-05-17T09:23:47.837 に答える
0

この解決策を試してください

with open('test', inplace=True) as text_file:
    for line in text_file:
         if line.rsplit('|', 1)[-1].strip() == 'number3':
             print '{}|{} \n'.format('this is replacement', 'number7')
         else:
             print line
于 2013-05-17T08:54:04.487 に答える