我有一个文本文件如下:
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
Run Code Online (Sandbox Code Playgroud)
我想在文件中搜索特定的行,假设该行是
song_path = "/run/media/dsankhla/Entertainment/English songs/Bad Meets Evil.mp3"
,然后我想寻找len(song_path)+2BEHIND 以便我可以指向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()
Run Code Online (Sandbox Code Playgroud)
如果您的文件不是太大(太大而无法放入内存,读/写速度很慢),您可以规避任何“低级”操作,例如搜索并完全读取您的文件,更改您想要更改的内容,然后写入一切都回来了。
# 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)
Run Code Online (Sandbox Code Playgroud)
随着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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12351 次 |
| 最近记录: |