Search code examples
pythonconfigparser

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.

I am writing an program in Linux and it communicates with an Windows 10 PC. I get an file from the Windows PC and with Python ConfigParser I set the new values. When I write it from Linux to Windows, the newlines are messed up. Is there a way to handle this nicely in Python 2.7?

EDIT 1: We have a txt file with configuration inside it we read it out from a raspberry Pi 3 running raspbarian.

[header]
source1 = variable1
source2 = variable2

if this is being read and written again the ouput is as folowing:

[header]source1 = variable1source2 = variable2

After this conversion our windows 10 pc txt reader can't read the file anymore.

EDIT 2: maybe this will help. This is the block of code from the 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")

Solution

  • Maybe not exactly the best way but I works now with the following method:

    In /usr/lib/python2.7/ConfigParser.py do the following:

    """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")