2013-12-20 3 views
4

저는 여전히 파이썬에서 학습자입니다. 특정 문자열을 찾아 파이썬에서 해당 문자열 뒤에 여러 문자열을 삽입 할 수 없었습니다. 파일의 라인을 검색하고 쓰기 기능의 내용을 삽입하고 싶습니다.문자열을 찾아 파이썬에서 그 뒤에 텍스트를 삽입하십시오.

나는 파일의 끝에 삽입하는 다음을 시도했습니다.

line = '<abc hij kdkd>' 
dataFile = open('C:\\Users\\Malik\\Desktop\\release_0.5\\release_0.5\\5075442.xml', 'a') 
dataFile.write('<!--Delivery Date: 02/15/2013-->\n<!--XML Script: 1.0.0.1-->\n') 
dataFile.close() 
+3

이 코드는 조금 혼란하는 데 도움이됩니다. 먼저 변수'line'을 어떤 텍스트 ('

+0

실제로 내가 어떤 파일에서 텍스트를 검색하기위한 if 문 시도하고 내가 적절한 결과 – Mallik

+0

을 얻을 NT 않았다 fetched.but되면 내가 텍스트를 삽입 할 것을 선 후 텍스트를 삽입 한 "<대인 수수 ..."후 " Mallik

답변

2

당신은 특정 패턴을 검색 할 re을 같은 파일의 올바른 위치를 수정 fileinput을 사용할 수는

import fileinput,re 

def modify_file(file_name,pattern,value=""): 
    fh=fileinput.input(file_name,inplace=True) 
    for line in fh: 
     replacement=value + line 
     line=re.sub(pattern,replacement,line) 
     sys.stdout.write(line) 
    fh.close() 

당신은이 같은이 기능 무언가를 호출 할 수 있습니다

modify_file("C:\\Users\\Malik\\Desktop\\release_0.5\\release_0.5\\5075442.xml", 
      "abc..", 
      "!--Delivery Date:") 
0

파이썬 문자열은 실제로 다음 - 당신은 입력 문자열의 첫 번째 부분이 새로 삽입 할 다음 텍스트를 만들 것입니다 입력 문자열을 수정하지 않을 즉, 불변 나머지 입력 문자열

당신은 당신이 찾고있는 텍스트의 위치를 ​​파이썬 문자열에 find 방법을 사용할 수 있습니다 : 당신은 여기

print insertAfter("Hello World", "lo", " beautiful") # prints 'Hello beautiful world' 
+0

건초 더미는 무엇인가 선언하거나 초기화해야합니까? – Mallik

+0

[이것은 건초 더미이다] (http://en.wikipedia.org/wiki/Haystack)와 [this is a needle] (http://en.wikipedia.org/wiki/Sewing_needle) :). 건초 더미는 파일 내용을 나타내며 검색하는 바늘을 바늘로 가리 킵니다. newText는 삽입하려는 것입니다.이것을 사용하려면, 파일의 전체 내용을 f.read()로 메모리에로드하고, 대체 내용을 작성하고 전체 내용을 다시 써야합니다 (쓰기 모드로 파일을 다시여십시오). – Cilyan

+0

haystack이 정의되지 않았다고 말하는이 코드를 실행하여 오류가 발생합니다. – Mallik

1

처럼 사용할 수

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

+0

동일한 파일에 출력을 쓰고 싶다면? – Mallik

+0

나는 대답을 업데이트했다 :) – Cilyan

0

Frerich 라베 ... 그것은 나를 위해 완벽하게 작동 ... 좋은 ... 감사합니다!

 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):] 


     with open(sddraft) as f1: 
      tf = open("<path to your file>", 'a+') 
      # Read Lines in the file and replace the required content 
      for line in f1.readlines(): 
       build = insertAfter(line, "<string to find in your file>", "<new value to be inserted after the string is found in your file>") # inserts value 
       tf.write(build) 
      tf.close() 
      f1.close() 
      shutil.copy("<path to the source file --> tf>", "<path to the destination where tf needs to be copied with the file name>") 

희망이 사람 :)

관련 문제