如何在没有默认Windows crlf的情况下生成py文件?
我如何从 python 编写一个 .py 文件,使其类型不应该像“带有 Windows CRLF 的 ASCII 文件”,
因为当我在 Windows 内运行 file.write(data)
时,它会写入该文件,但是当我尝试 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]:
how can I write a .py file from python such that its type should not be like 'ASCII file with Windows CRLF'
because when i run file.write(data)
inside windows it write the file but when I try toeval(open(file.py).read())
it fails and gives syntax error because of windows CRLF on each line......
see the error log - traceback
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]:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以:
open(file, 'wb')
打开文件以二进制模式写入文件,或者...data 等写入之前,从字符串中去除 CR-LF .replace('\r','')
我会避开
exec
并使用execfile
正如 SilentGhost 提到的。You can:
open(file, 'wb')
or...data.replace('\r','')
I would steer clear of
exec
and useexecfile
as mentioned by SilentGhost.问题不在于 CRLF,而在于
eval
用于评估单个表达式,而不是整个程序。您可以使用
exec
从字符串执行程序,或使用execfile
直接从文件执行程序。无论如何,要回答您最初的问题,您可以通过以二进制模式打开文件来避免编写 CRLF:
f = open(filename, 'wb')
The problem is not with the CRLF, but that
eval
is for evaluating a single expression, not an entire program.You can use
exec
to execute a program from a string, orexecfile
to execute it directly from a file.To answer your original question anyway, you can avoid writing CRLF by opening the file in binary mode:
f = open(filename, 'wb')
我认为您正在寻找
execfile
函数。I think you're looking for
execfile
function.只需以二进制模式打开文件:
open("myfile.py", "rwb")
Just open the file in binary mode:
open("myfile.py", "rwb")