簡體   English   中英

Python - 寫入python文件?

[英]Python - writing to python files?

是否有一些更方便的方式來寫入python文件比使用讀/寫任何文件(如txt文件等)。

我的意思是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

換句話說,write應該只修改version密鑰值,其他所有內容都應該像編寫前一樣保存。

我提出了解決方案。 它不是很干凈,但它的工作原理。 如果有人有更好的答案,請寫下來。

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)

為了修改配置文件,你可以這樣做:

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函數實際上是寫入文件。 有關打印功能如何為您寫作的更多詳細信息,請參見此處

我希望它有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM