2013-12-20 35 views
4

我仍然學習python。我無法找到一個特定的字符串,並在Python中的字符串之後插入多個字符串。我想搜索文件中的行並插入寫入功能的內容查找一個字符串並在Python中插入文本

我已經嘗試了以下插入文件末尾的內容。

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

我想在文本「 Mallik

回答

2

您可以使用fileinput修改同一個文件就地和re搜索特定模式

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

Python中的字符串是不可變的,這意味着你不會實際修改輸入字符串 - 你將創建一個新的具有輸入字符串的第一部分,那麼你要插入的文本,然後輸入字符串的其餘部分。

您可以使用Python中的find方法來找到你要找的文字:

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

你可以使用它像

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

我需要申報或初始化什麼是乾草堆? – Mallik

+0

[這是乾草堆](http://en.wikipedia.org/wiki/Haystack)和[這是一個針](http://en.wikipedia.org/wiki/Sewing_needle):)。 Haystack代表您的文件內容並針對您搜索的行。 newText是你想要插入的。要使用它,你必須使用f.read()將文件的全部內容加載到內存中,進行替換並將全部內容寫回(在寫模式下重新打開文件)。 – Cilyan

+0

通過運行這段代碼它說haystack沒有被定義,所以這是我得到的錯誤 – Mallik

1

這裏是處理文件的建議,我猜想你搜索的模式是一條完整的線(線上沒有比模式更多的東西,模式也適合於一條線)。

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

此代碼是Python 3中,可能需要Python 2中,尤其是with聲明(見contextlib.nested一些修改。如果你的模式在一行中配合,但不是整個行,你可以使用"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>") 

希望這可以幫助別人:)

相關問題