Python .cpp读取,追加,保存和关闭,但不工作
python .cpp read, append, save and close but dont works
我是初学者,有以下任务:
- 要搜索.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模块中更详细地检查,我认为这只是一个简单的例子。如果问题解决了,请在我的答案上做个记号。
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 如何使用OpenCV将RBG图像转换为HSV,并将H、S和V值保存为C++中的3个独立图像
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- EvtExportLogneneneba API正在将远程计算机的事件日志保存到远程PC本身.如何将其保存到主机
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 如何将子窗口(MFC 应用程序)的工作区保存到图像
- 从Windows注册表中保存的工作区检索窗口放置
- 如何在不保存文件的情况下制作打印屏幕并将其发送到FTP服务器?我的工作代码将文件保存到HDD
- 在C++应用程序中保存/加载工作区
- 日蚀。不同的工作区。无法保存相同的项目名称
- Python .cpp读取,追加,保存和关闭,但不工作
- 保存工作区MFC C++MDI