【问题标题】:How to seek to a specific line in a file?如何查找文件中的特定行?
【发布时间】:2016-11-11 10:49:04
【问题描述】:

我有一个文本文件如下:

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,以便我可以在文件中指向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()

【问题讨论】:

  • 如果您的文件不是太大并且您可以在内存中完整地读取它,您可以使用readlines() 并简单地查看第 n+1 行。
  • @syntonym 代码的答案会很有帮助
  • @syntonym 即使我需要更改文件中的那一行。

标签: python file seek


【解决方案1】:

如果您的文件不是太大(太大而无法放入内存,读/写速度很慢),您可以绕过任何“低级”操作,例如搜索,只需完全读取您的文件,更改您想要更改的内容,然后将所有内容写回。

# 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,当你不写“byte 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

【讨论】:

    【解决方案2】:

    最好的方法是使用 seek,就像这个例子:

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

    【讨论】:

      猜你喜欢
      • 2016-06-29
      • 1970-01-01
      • 2012-09-22
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 1970-01-01
      • 2017-06-05
      • 2018-04-29
      相关资源
      最近更新 更多