2016-11-11 10 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 

내가의이 라인이
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

당신은 당신이 할 수있는 메모리에 completly를 읽을 수 있습니다 : 당신은 즉, "바이트 PERFEKT"를 작성하지 않는 경우 seek

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

당신은 신중해야 'readlines()'를 사용하고 간단히 n + 1 라인을보십시오. – syntonym

+0

@syntonym 코드로 대답하면 도움이 될 것입니다 – dlps

+0

@syntonym조차도 파일에서 해당 줄을 변경해야합니다. – dlps

답변

0

파일이 너무 커서 (메모리에 저장하기에는 너무 커서 읽기/쓰기가 느리다) 검색을하고 "파일 읽기"와 같은 "저급"동작을 피할 수 있으면 원하는 내용을 변경하십시오. 변경하고 모든 것을 다시 쓰십시오. 파일이 너무 크지 않으면

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을 사용하면 뒤로 이동할 수 있습니다.