为什么 .cfg 没有被重写,而是创建了新文件?

Why .cfg doesn't get to be re-written, but the new file was created instead?

请给我解释一下好吗

我有一部分代码使用了 ConfigParser 我正在目录中读取的文件 ~/ui/config.cfg 在我调用下面的函数之后,我在我的模块所在的目录中得到一个新文件,它是 (~/ui/helper/config.cfg)

class CredentialsCP:

    def __init__(self, cloud_name=None):
       self.config = ConfigParser.ConfigParser()
       self.cloud_name = cloud_name

    def rewrite_pass_in_config(self, cloud, new_pass):
        if new_pass:
           self.config.read('config.cfg')
           self.config.set(cloud, 'password', new_pass)
           with open('config.cfg', 'wb') as configfile:
            self.config.write(configfile)
        else:
           return False

它在我 运行 我的代码所在的目录中创建了一个新文件,但我需要重写相同的文件。我怎样才能做到这一点?为什么我一直有同样的行为?

由于您在读取和写入时使用相同的文件名 (config.cfg(并且不更改工作目录),因此您正在操作同一个文件。由于您正在编写 ~/ui/helper/config.cfg 文件(它是在 运行 代码之后创建的),这也是您正在阅读的文件。

因此,您没有打开(阅读)您自认为的文件。来自 [Python]: read(filenames, encoding=None)

If a file named in filenames cannot be opened, that file will be ignored.
...
If none of the named files exist, the ConfigParser instance will contain an empty dataset.

您正在从一个不存在的文件中读取,这会产生一个空配置,这就是您在(所需)文件中写入的配置。为了解决您的问题,请通过 全名或相对名称 指定所需的文件。你可以有这样的东西:

  • __init__中:

    self.file_name = os.path.expanduser("~/ui/config.cfg") # Or any path processing code
    
  • rewrite_pass_in_config:

    • 阅读:

      self.config.read(self.file_name)
      
    • 写入

      with open(self.file_name, "wb") as configfile:
          self.config.write(configfile)