hexagon logo

Converting code to Python 3

Ho folks,
I'm about to check our code for future usage with ADAMS 2018 which uses Python 3 . (It's working as is in Python 2.x)
 
This code that's used to do a dos2unix on Windoze machines throws errors that I can't resolve:
 
import os, sys, string
import re
 
# In_File = File to be converted
In_File = 'test.txt'
# -----------------------------------
# Convert to unix
# -----------------------------------
data = open(In_File, "rb").read()
newdata = re.sub("\r\n", "\n", data)
if newdata != data:
   print('   ' + In_File + " \tis converted to unix format ...")
   f = open(In_File, "wb")
   f.write(newdata)
   f.close()
 
Any proposals for replacing
re.sub("\r\n", "\n", data)
that may work ?
 
Parents
  • Using bytestrings for ascii text isn't a good idea, you should leave it in unicode. Just read and write the file using the default encoding, but with an explicit "newline" on the write:
     
    with open(in_file, "r") as input:
    data = input.read()
    with open(out_file, "w", newline="\n") as output:
    output.write(data)
     
    (Where the hell is the BBcode-like [code] block on this crappy forum?)
Reply
  • Using bytestrings for ascii text isn't a good idea, you should leave it in unicode. Just read and write the file using the default encoding, but with an explicit "newline" on the write:
     
    with open(in_file, "r") as input:
    data = input.read()
    with open(out_file, "w", newline="\n") as output:
    output.write(data)
     
    (Where the hell is the BBcode-like [code] block on this crappy forum?)
Children
No Data