简体   繁体   中英

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

In your call to read the file-like object, you should be passing in the U flag for cross-compatibility. eg

import ConfigParser

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

Per the 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'.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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