代码之家  ›  专栏  ›  技术社区  ›  shahjapan

如何生成没有默认Windows CRLF的py文件?

  •  1
  • shahjapan  · 技术社区  · 16 年前

    我如何从python编写一个.py文件,使其类型不象“带Windows CRLF的ASCII文件”

    因为当我跑步时 file.write(data) 在Windows中写入文件,但当我尝试 eval(open(file.py).read()) 由于每行的Windows CRLF,它失败并给出语法错误……

    请参阅错误日志-回溯

    ERROR:web-services:[25]:     info = eval(tools.file_open(terp_file).read(-1))
    ERROR:web-services:[26]:   File "<string>", line 1
    ERROR:web-services:[27]:     {
    ERROR:web-services:[28]:
    
    4 回复  |  直到 16 年前
        1
  •  1
  •   Community Mohan Dere    9 年前

    你可以:

    1. 以二进制模式写入文件,方法是用 open(file, 'wb') 或者…
    2. 在用类似于 data.replace('\r','')

    我会避开 exec 和使用 execfile as mentioned by SilentGhost

        2
  •  1
  •   interjay    16 年前

    问题不在于CRLF,而是 eval 用于计算单个表达式,而不是整个程序。

    你可以用 exec 从字符串执行程序,或 execfile 直接从文件执行。

    要回答原始问题,可以通过以二进制模式打开文件来避免写入CRLF: f = open(filename, 'wb')

        3
  •  1
  •   SilentGhost    16 年前

    我想你在找 execfile 功能。

        4
  •  0
  •   Rakis    16 年前

    只需以二进制模式打开文件: open("myfile.py", "rwb")