dlps dlps - 26 days ago 5
Python Question

How to seek to a specific line in a file?

I have a text file as follows:

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


I want to search for a specifc line in the file let's say the line is

song_path = "/run/media/dsankhla/Entertainment/English songs/Bad Meets Evil.mp3"


and then I want to seek
len(song_path)+2
BEHIND so that I can point to
3
in the file. How can I do this?

This is my code so far:

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

Answer

If your file isn't too large (too large to fit in memory, pretty slow to read/write) you can circumvent any "low level" actions like seek and just read your file completely, change what you want to change, and write everything back.

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

With seek you need to be careful when you don't write "byte perfekt", i.e:

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