2013-12-20 40 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>") 

希望这可以帮助别人:)

相关问题