2016-11-11 16 views
-1

次のように私は、テキストファイルを持っている:私は、ファイルにspecifc行を検索したいファイル内の特定の行を検索するにはどうすればよいですか?

1 
/run/media/dsankhla/Entertainment/English songs/Apologise (Feat. One Republic).mp3 
3 
/run/media/dsankhla/Entertainment/English songs/Bad Meets Evil.mp3 
5 
/run/media/dsankhla/Entertainment/English songs/Love Me Like You DO.mp3 

はのは、ラインが
song_path = "/run/media/dsankhla/Entertainment/English songs/Bad Meets Evil.mp3"
され、その後、私は私ができるようにlen(song_path)+2 BEHINDを追求したいとしましょうファイル内の3をポイントします。これどうやってするの?
これは、これまでの私のコードです:

txt = open(".songslist.txt", "r+") 
if song_path in txt.read(): 
    byte = len(song_path) 
    txt.seek(-(byte), 1) 
    freq = int(txt.readline()) 
    print freq  # 3 
    freq = freq + 1 
    txt.seek(-2,1) 
    txt.write(str(freq)) 
    txt.close() 
+0

あなたのファイルが大きすぎではない、あなたはあなたができるメモリにcompletlyそれを読むことができる場合:あなたはすなわち、「バイトPERFEKT」を書いていないときに注意する必要がありseek

# read everything in with open(".songslist.txt", "r") as f: txt = f.readlines() # modify path_i = None for i, line in enumerate(txt): if song_path in line: path_i = i break if path_i is not None: txt[path_i] += 1 # or what ever you want to do # write back with open(".songslist.txt", "w") as f: f.writelines(txt) 

'readlines()'を使い、単にn + 1行目を見てください。 – syntonym

+0

@syntonymコードの答えは役に立ちます – dlps

+0

@syntonymでもファイル内のその行を変更する必要があります。 – dlps

答えて

0

ファイルが大きすぎず(大きすぎてメモリに収まらない、読み込み/書き込みがかなり遅い)、シークのような「低レベル」のアクションを回避し、ファイルを完全に読み取るだけで、変更し、すべてを書き戻します。

f = open("test", "r+") 
f.write("hello world!\n12345") 
f.seek(6) # jump to the beginning of "world" 
f.write("1234567") # try to overwrite "world!" with "1234567" 
# (note that the second is 1 larger then "world!") 
f.seek(0) 
f.read() # output is now "hello 123456712345" note the missing newline 
0

最良の方法は、この例のように、求めて使用することです:

fp = open('myfile') 
last_pos = fp.tell() 
line = fp.readline() 
while line != '': 
    if line == 'SPECIAL': 
    fp.seek(last_pos) 
    change_line()#whatever you must to change 
    break 
    last_pos = fp.tell() 
    line = fp.readline() 

あなたが変数に位置値を割り当てるためにfp.tellを使用する必要があります。その後、fp.seekであなたは後ろに行くことができます。

関連する問題