2016-11-11 41 views
-1

我有一個文本文件,如下所示:如何尋求到一個文件中的特定行?

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 

我要搜索的文件中specifc線假設該行是
song_path = "/run/media/dsankhla/Entertainment/English songs/Bad Meets Evil.mp3"
,然後我想尋求len(song_path)+2之後,以便我能指向文件中的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

,你可以在內存中就可以完全地讀它使用'readlines()',並簡單地在第n + 1行中查找。 – syntonym

+0

@syntonym與代碼的答案將有助於 – dlps

+0

@syntonym即使我需要改變該行的文件中。 – dlps

回答

0

如果你的文件不是太大(太大,不適合在內存中,相當緩慢的讀/寫),你可以規避喜歡尋求任何「低水平」的行動和剛剛看了你的文件完全改變你想要什麼改變,並寫回所有的東西。

# 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) 

隨着seek你必須要小心,當你不寫「字節PERFEKT」,即:如果你的文件是不是太大

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你可以倒退。

相關問題