Python 配置解析器读写

Python 配置解析器读写,python,configparser,read-write,Python,Configparser,Read Write,我正在使用Python3.2和configparser模块,遇到了一些问题。我需要先读取,然后写入配置文件。我尝试了以下方法: import configparser data = open('data.txt', 'r+') a = configparser.ConfigParser() a.read_file(data) a['example']['test'] = 'red' a.write(data) 如果你真的关心这个问题,你可以写一个临时文件,然后将临时文件重命名为这个文件-如果配置

我正在使用Python3.2和configparser模块,遇到了一些问题。我需要先读取,然后写入配置文件。我尝试了以下方法:

import configparser data = open('data.txt', 'r+') a = configparser.ConfigParser() a.read_file(data) a['example']['test'] = 'red' a.write(data)
如果你真的关心这个问题,你可以写一个临时文件,然后将临时文件重命名为这个文件-如果配置写入失败,原始文件将不会被更改;rename/move通常是原子的,不过在Windows下,您可能需要直接调用MoveFileEx,而不是使用os.rename,因此您可以确保您将拥有旧内容或新内容,并且文件不会处于任何其他状态,当然也不会出现底层文件系统的任何严重故障

# ...
a['example']['test'] = 'red'

import tempfile, os
with tempfile.NamedTemporaryFile() as tmp:
    a.write(tmp)

    # or ctypes.windll.kernel32.MoveFileExW(tmp.name, 'data.txt', 2)
    # 2 = MOVEFILE_REPLACE_EXISTING 
    # I'll leave wrapping it in a cross-platform manner up to you
    os.rename(tmp.name, 'data.txt')

当我遇到类似的情况时,我会这样做

import configparser
data = open('data.txt', 'r+')
a = configparser.ConfigParser()
a.read_file(data)
a['example']['test'] = 'red'
data.truncate(0)#<--
data.seek(0)#<--
a.write(data)
这会导致文件对象被截断为零。然后重置指向文件开头的指针。之后,configparser可以像正常一样处理空文件对象


应该注意的是,我是在Python 3中完成的。

谢谢!那是个好主意。不过,太糟糕了,Windows使用了另一个操作。我认为应该是tempfile.mkstemp[-1]或tempfile.mktemp,但第二个操作不安全…,而不是2
# ...
a['example']['test'] = 'red'

import tempfile, os
with tempfile.NamedTemporaryFile() as tmp:
    a.write(tmp)

    # or ctypes.windll.kernel32.MoveFileExW(tmp.name, 'data.txt', 2)
    # 2 = MOVEFILE_REPLACE_EXISTING 
    # I'll leave wrapping it in a cross-platform manner up to you
    os.rename(tmp.name, 'data.txt')
import configparser
data = open('data.txt', 'r+')
a = configparser.ConfigParser()
a.read_file(data)
a['example']['test'] = 'red'
data.truncate(0)#<--
data.seek(0)#<--
a.write(data)