views:

58

answers:

4

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 to eval(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]:
+1  A: 

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, or execfile 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')

interjay
+1  A: 

I think you're looking for execfile function.

SilentGhost
A: 

Just open the file in binary mode: open("myfile.py", "rwb")

Rakis
+1  A: 

You can:

  1. Write the file in binary mode by opening it with open(file, 'wb') or...
  2. Strip the CR-LFs from the string before writing it with something like data.replace('\r','')

I would steer clear of exec and use execfile as mentioned by SilentGhost.

D.Shawley
Thanks D.Shawley I don't know why but it worked with 'wb' it,it should also work for 'w' - anyhow thanks for your immediate help !
Tumbleweed
@shahjapan - there is a good Wikipedia link (http://en.wikipedia.org/wiki/Newline#In_programming_languages) that describes the differences between _"binary mode"_ and _"text mode"_.
D.Shawley