有没有比对任何文件(如txt文件等)使用读/写更方便的方式写入python文件。在
我的意思是python知道python文件的实际结构,所以如果我需要写入它,也许有更方便的方法来完成它?在
如果没有这样的方法(或者太复杂了),那么通常只使用normalwrite
修改python文件的最佳方法是什么(下面的示例)?在
我在我的子目录中有很多这样的文件叫做:
__config__.py
这些文件用作配置。他们有未分配的python字典,如下所示:
{
'name': 'Hello',
'version': '0.4.1'
}
所以我需要做的是,写所有这些__config__.py
文件的新版本(例如'version': '1.0.0'
)。在
更新
更具体地说,假设有一个python文件,其内容如下:
^{pr2}$现在运行一些python脚本,修改给定的字典,写入python文件后,输出如下:
# Some important comment
# Some other important comment
{
'name': 'Hello',
'version': '1.0.0'
}
# Some yet another important comment
所以换句话说,write应该只修改version
键值,其他的一切都应该保持在写之前的状态。在
要修改配置文件,只需执行以下操作:
请注意,这里的print函数实际上写入了一个文件。 有关print函数如何为您编写的详细信息,请参见here
我希望有帮助。在
我想出了解决办法。它不是很干净,但很管用。如果有人有更好的答案,请写下来。在
相关问题 更多 >
编程相关推荐