繁体   English   中英

Python 2.7 Linux \\ n到Windows \\ r \\ n

[英]Python 2.7 Linux \n to Windows \r\n

解决方案:更改ConfigParser.py带有\\ n的所有内容都应为\\ r \\ n,这样linux和Windows可以读取带有行返回的文件。 这为我们解决了。

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

编辑1:我们有一个内部配置的txt文件,我们从运行树莓派的树莓派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 = %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文档

除了标准的fopen()值模式外,还可以是“ U”或“ rU”。 Python通常是通过通用换行符支持构建的。 提供“ U”会以文本文件的形式打开文件,但是行可能会被以下任一终止:Unix行尾约定“ \\ n”,Macintosh约定“ \\ r”或Windows约定“ \\” 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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM