처럼 사용할 수
def insertAfter(haystack, needle, newText):
""" Inserts 'newText' into 'haystack' right after 'needle'. """
i = haystack.find(needle)
return haystack[:i + len(needle)] + newText + haystack[i + len(needle):]
하는 파일을 처리 할 수있는 제안이다 , 당신이 검색 한 패턴이 전체 라인이라고 가정합니다 (라인보다 패턴에 더 많은 것이없고 패턴이 한 라인에 들어 맞습니다). 파이썬 3, 약간의 수정이 특히 with
문 파이썬 2 (contextlib.nested를 참조 필요할 수 있습니다에 대한
line = ... # What to match
input_filepath = ... # input full path
output_filepath = ... # output full path (must be different than input)
with open(input_filepath, "r", encoding=encoding) as fin \
open(output_filepath, "w", encoding=encoding) as fout:
pattern_found = False
for theline in fin:
# Write input to output unmodified
fout.write(theline)
# if you want to get rid of spaces
theline = theline.strip()
# Find the matching pattern
if pattern_found is False and theline == line:
# Insert extra data in output file
fout.write(all_data_to_insert)
pattern_found = True
# Final check
if pattern_found is False:
raise RuntimeError("No data was inserted because line was not found")
이 코드입니다. 당신의 패턴을 한 줄에 적합하지만, 전체 라인, 대신 "theline in line"
를 사용할 수없는 경우 "theline == line"
. 패턴이 두 줄 이상으로 퍼질 수있는 경우 더 강력한 알고리즘이 필요합니다. :)
동일한 파일에 쓰려면 다른 파일에 쓸 수 있으며 입력 파일을 통해 출력 파일을 이동할 수 있습니다. 이 코드를 공개 할 계획은 없었지만 며칠 전 같은 상황이었습니다. 그래서 여기에 입력 파일에 쓰기이 개 태그와 지원 사이의 파일에 내용을 삽입하는 클래스입니다 : https://gist.github.com/Cilyan/8053594
이 코드는 조금 혼란하는 데 도움이됩니다. 먼저 변수'line'을 어떤 텍스트 ('
실제로 내가 어떤 파일에서 텍스트를 검색하기위한 if 문 시도하고 내가 적절한 결과 – Mallik
을 얻을 NT 않았다 fetched.but되면 내가 텍스트를 삽입 할 것을 선 후 텍스트를 삽입 한 "<대인 수수 ..."후 "
Mallik