rnd om
rnd om

Reputation: 355

with python, how can i convert a txt file on windows to a unix type?

often times, i forget to change the document type(?) to unix, instead of windows before loading to a linux environment.

when i run the file from there, i get:

filename.sh: line 4: $'\r': command not found

is there a way to change the text file from python?

ideally, through a sub process on the command line or something that doesn't require me to open the file and add EOL stuff?

otherwise, is there a way to build that into a return from the subprocess?

because if i do $? i get 0 after running a text that is not formatted correctly.

edit:

something weird is happening - i was originally testing this out in linux and was getting that 'error'. when i run plink on a the same file, it actually reads it like unix and runs it correctly...

Upvotes: 1

Views: 1138

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177971

Yes, with the newline parameter of open. By default open uses universal newline when text mode is used, and converts all new line types (\r, \n, \r\n) to \n. Read the whole file in, then write it out again with a specified newline:

Example (overwrites original file!):

import sys

with open(sys.argv[1]) as f:  # default is 'rt' read text mode.
    data = f.read()

with open(sys.argv[1], 'w', newline='\n') as f: # write with Unix new lines.
    f.write(data)

Also, without newline specified it will use the platform default, so on Windows it will write \r\n endings, and on Unix it will write \n endings if you leave the parameter out.

Upvotes: 2

Related Questions