Python .cpp读取,追加,保存和关闭,但不工作

python .cpp read, append, save and close but dont works

本文关键字:工作 保存 cpp 读取 追加 Python      更新时间:2023-10-16

我是初学者,有以下任务:

  • 要搜索.cpp文件(文本)的目录(文件夹)"完成"
  • 打开文件中的
  • ,搜索某个字符串,发现"done"
  • 之后找到的值将被另一个替换(追加)"部分"
  • 最后存储并关闭"also works"

问题是,我的脚本找到相应的条目,它也改变了"然而,之前和之后的一切都是"删除"我需要改变什么?

谢谢。

import re    
with open("test.cpp", "r+") as f:
match = re.search("^(?P<Text1>.*)COMPILE_TIME_ASSERT(s*(?P<Text2>.+),(?P<Text3>s*)(?P<Text4>S*)(?P<Text5>s*)s*;s*)",               "COMPILE_TIME_ASSERT(TABLE_LENGTH(PopupType2ActionID) == EPopupType::ARRAY_SIZE , PopupType2ActionID_table_needs_revision);")
result = '"' + match.group('Text4') + '"'
如果匹配

:

print("%sPCC_STATIC_ASSERT(%s,%s%s" % (match.group('Text1'), 
match.group('Text2'), result, match.group('Text5')))
f.write("%sPCC_STATIC_ASSERT(%s,%s%s" % (match.group('Text1'), match.group('Text2'), result, match.group('Text5')))
f.close()

如果我理解正确,您正在寻找字符串->匹配,然后创建一个新字符串。

不幸的是,你这样做是不合适的(无论你使用什么编程语言)。这是因为你的文件是以r+打开的,但是当你写这一行的时候,其余的都被删除了:-)

为了正确地做到这一点,你需要有一个源文件和一个目标文件,否则你只需要用一行替换整个文件:

f.write("%sPCC_STATIC_ASSERT(%s,%s%s" % (match.group('Text1'), match.group('Text2'), result, match.group('Text5'))) 

好的,你可以这样做,只是给它一个尝试:1)将原始文件移动到文件中~(就像Microsoft Word所做的那样):

import shutil
shutil.move( afile, afile+"~" )
destination= open( aFile, "w" )
source= open( aFile+"~", "r" )

2)现在你将只从原来的文件中"读",并写入一个新的文件,具有原来的名称;)

3)为方便起见,您现在可以逐行读取原始文件和:

for line in source:
    match = re.search(Your_matching, line)
    if <matching_condition>:
        destination.write( <New_LINE_after_match> + "n" )
    else:
    # All the other lines without match, just write back same line
        destination.write(line)
source.close()
destination.close()

这已经足够生成一个合适的文件了。然后可以删除~文件:-)

这是在python中可以做到的一种方式:-)否则使用linux cli中的sed命令修改文件:-)

希望这能澄清你的疑问并解决你的问题。祝你今天愉快!

下面是一个简单的例子。在txt文件中,我有简单的名字:约翰彼得马可米奇弗兰克。
import re,shutil,os
aFile = "marco.txt"
shutil.move( aFile, aFile+"~" )
destination= open(aFile, "w+" )
source= open(aFile+"~", "r" )
for line in source:
    match = re.search("Marco", line)
    if match:
        destination.write( "Modified_Line" + "n" )
    else:
    # All the other lines without match, just write back same line
        destination.write(line)
source.close()
destination.close()
os.remove(aFile+"~")

运行程序后,将输出mark .txt文件:

 John
 Peter
 Modified_Line
 Mickey
 Frank

在你的情况下,这应该解决问题。最大的问题可能是你的匹配部分。你必须在re模块中更详细地检查,我认为这只是一个简单的例子。如果问题解决了,请在我的答案上做个记号。