繁体   English   中英

解析文件并附加字符串 python

[英]parsing file and appending string python

假设我有一个文件:

This is the first line
Ages = ["young*","old*"] //This was the second line, I put a * on purpose
This is the third line

场景如下:

  1. 我知道文件中有“Ages”数组,但我不知道它的元素。
  2. 我现在想 append 一个特定的字符串,在每个元素之后说“test*”,文件将变为:
This is the first line
Ages = ["young\*test\*","old\*test\*"] //This was the second line, I put a * on purpose
This is the third line

有什么帮助吗?

首先,您需要以读写模式打开文件并将其全部读取为字符串,然后我认为您最好的选择是使用正则表达式对要替换的内容进行分组并替换它。 然后将其写回文件。 这将类似于以下内容:

pattern = re.compile(r'') # this would be your pattern
with open("filename.txt", "r+") as file:
    content = file.read() #all the content as string
    replaced = pattern.sub('the match group with your addition', content)
    file.seek(0) #the seek is necessary to return back to the start of the file
    file.write(replaced) # write the modified content to the file
    file.truncate() # truncate if there are any trailing parts from before

我认为这是一个家庭作业,所以我不会在那里完成正则表达式模式,但我会给出提示:

带有尾随 0 或更多空格的年龄 = 带有尾随 0 或更多空格的数组开放字符,其中包含内部数组元素的匹配组,以及表示每个元素结束的另一个内部组,然后您可以相应地替换它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM