Python 2.7 Linux \n Windows \r\n

Python 2.7 Linux \n to Windows \r\n

SOLUTION: Change ConfigParser.py Everything with \n should be \r\n, this way linux and windows can read the file with line return. This fixed it for us.

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

编辑 1: 我们有一个包含配置的 txt 文件,我们从 raspberry Pi 3 运行 raspbarian.

中读取它
[header]
source1 = variable1
source2 = variable2

如果再次读写,输出如下:

[header]source1 = variable1source2 = variable2

转换后我们的 windows 10 pc txt reader 无法再读取文件。

编辑 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 = %s\n" % (key, str(value).replace('\n', '\n\t')))
        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', '\n\t')))
            fp.write("%s\n" % (key))
        fp.write("\n")

在读取类文件对象的调用中,您应该传入 U 标志以实现交叉兼容性。例如

import ConfigParser

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

根据 2.7 documentation:

In addition to the standard fopen() values mode may be 'U' or 'rU'. Python is usually built with universal newlines support; supplying 'U' opens the file as a text file, but lines may be terminated by any of the following: the Unix end-of-line convention '\n', the Macintosh convention '\r', or the Windows convention '\r\n'.

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

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

"""Write an .ini-format representation of the configuration state."""
        if self._defaults:
            fp.write("[%s]\r\n" % DEFAULTSECT)
            for (key, value) in self._defaults.items():
                fp.write("%s = %s\r\n" % (key, str(value).replace('\n', '\n\t')$
            fp.write("\r\n")
        for section in self._sections:
            fp.write("[%s]\r\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', '\n\t')$
                fp.write("%s\r\n" % (key))
            fp.write("\r\n")