是否有比对任何文件(如txt文件等)使用读/写更方便的方法来写入python文件。
我的意思是python知道python文件的结构实际上是什么,所以如果我需要写入它,也许有更方便的方法来完成它?
--如果没有这样的方式--(或者它太复杂了),那么通常只使用普通write (下面的例子)来修改python文件的最佳方法是什么?
我的子目录中有很多这样的文件,名为:
__config__.py
这些文件用作配置。他们有未指定的python字典,如下所示:
{
'name': 'Hello',
'version': '0.4.1'
}因此,我需要做的是将所有这些__config__.py文件写入新版本(例如'version': '1.0.0')。
更新
更确切地说,考虑到有一个python文件,其内容如下:
# Some important comment
# Some other important comment
{
'name': 'Hello',
'version': '0.4.1'
}
# Some yet another important comment现在运行一些python脚本,它应该写入python文件,修改给定的字典,编写之后,输出应该如下所示:
# Some important comment
# Some other important comment
{
'name': 'Hello',
'version': '1.0.0'
}
# Some yet another important comment因此,换句话说,写应该只修改version键值,其他一切都应该保持在编写之前的状态。
发布于 2016-06-23 12:00:49
我想出了解决办法。它不是很干净,但很管用。如果有人有更好的答案,请写出来。
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)发布于 2016-06-23 12:27:47
为了修改配置文件,您可以这样做:
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函数实际上是写到文件中的。有关如何为您编写打印函数的详细信息,请参阅here。
希望能帮上忙。
https://stackoverflow.com/questions/37984952
复制相似问题