Python写入Python文件?

2024-10-01 00:34:24 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有比对任何文件(如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键值,其他的一切都应该保持在写之前的状态。在


Tags: 文件方法namepytxtconfighello字典
2条回答

要修改配置文件,只需执行以下操作:

import fileinput

lines = fileinput.input("__config__.py", inplace=True)
nameTag="\'name\'"
versionTag="\'version\'"
name=""
newVersion="\'1.0.0\'" 
for line in lines:
    if line[0] != "'":
        print(line)
    else:
        if line.startswith(nameTag):
            print(line)
            name=line[line.index(':')+1:line.index(',')]
        if line.startswith(versionTag):
            new_line = versionTag + ": " + newVersion
            print(new_line)

请注意,这里的print函数实际上写入了一个文件。 有关print函数如何为您编写的详细信息,请参见here

我希望有帮助。在

我想出了解决办法。它不是很干净,但很管用。如果有人有更好的答案,请写下来。在

content = ''
file = '__config__.py'
with open(file, 'r') as f:
    content = f.readlines()
    for i, line in enumerate(content):
        # Could use regex too here
        if "'version'" in line or '"version"' in line:
            key, val = line.split(':')
            val = val.replace("'", '').replace(',', '')
            version_digits = val.split('.')
            major_version = float(version_digits[0])
            if major_version < 1:
                # compensate for actual 'version' substring
                key_end_index = line.index('version') + 8
                content[i] = line[:key_end_index] + ": '1.0.0',\n"
with open(file, 'w') as f:
    if content:
        f.writelines(content)

相关问题 更多 >