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

相关问题