Python 2.7 Linux to Windows



溶液: 更改 ConfigParser.py 带有 的所有内容都应该是 \r,这样 Linux 和 Windows 就可以读取带有行返回的文件。 这为我们修复了它。

我正在用Linux编写一个程序,它与Windows 10 PC通信。我从Windows PC获取一个文件,并使用Python ConfigParser设置新值。当我把它从Linux写到Windows时,换行符被搞砸了。有没有办法在 Python 2.7 中很好地处理这个问题?

编辑 1:我们有一个带有配置的 txt 文件,我们从运行树莓派 3 的树莓派 3 中读出它。

[header]
source1 = variable1
source2 = variable2

如果再次读取和写入,则输出为:

[header]source1 = variable1source2 = variable2

在此转换之后,我们的 windows 10 pc txt 阅读器无法再读取该文件。

编辑2:也许这会有所帮助。这是 ConfigParser.py 中的代码块:

  def write(self, fp):
    """Write an .ini-format representation of the configuration state."""
    if self._defaults:
        fp.write("[%s]n" % DEFAULTSECT)
        for (key, value) in self._defaults.items():
            fp.write("%s = %sn" % (key, str(value).replace('n', 'nt')))
        fp.write("n")
    for section in self._sections:
        fp.write("[%s]n" % section)
        for (key, value) in self._sections[section].items():
            if key == "__name__":
                continue
            if (value is not None) or (self._optcre == self.OPTCRE):
                    key = " = ".join((key, str(value).replace('n', 'nt')))
            fp.write("%sn" % (key))
        fp.write("n")

在调用类似文件的对象时,应传入 U 标志以实现交叉兼容性。 例如

import ConfigParser
conf = ConfigParser.ConfigParser()
conf.readfp(open('/tmp/settings.cfg', 'U'))
...

根据 2.7 文档:

除了标准的 fopen() 值模式可以是"U"或"rU"。 Python 通常使用通用换行符支持构建;供应"U" 将文件作为文本文件打开,但行可能会被以下任何行终止 以下内容:Unix 行尾约定 '',Macintosh 约定"\r"或 Windows 约定"\r"。

也许不完全是最好的方法,但我现在使用以下方法:

在/usr/lib/python2.7/ConfigParser.py执行以下操作:

"""Write an .ini-format representation of the configuration state."""
        if self._defaults:
            fp.write("[%s]rn" % DEFAULTSECT)
            for (key, value) in self._defaults.items():
                fp.write("%s = %srn" % (key, str(value).replace('n', 'nt')$
            fp.write("rn")
        for section in self._sections:
            fp.write("[%s]rn" % section)
            for (key, value) in self._sections[section].items():
                if key == "__name__":
                    continue
                if (value is not None) or (self._optcre == self.OPTCRE):
                        key = " = ".join((key, str(value).replace('n', 'nt')$
                fp.write("%srn" % (key))
            fp.write("rn")

最新更新