[英]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.