[Pythonmac-SIG] [HELP!] PC Line Endings? Batch file replacement

Ryan Wilcox ryanwilcox@mac.com
Thu, 21 Feb 2002 12:24:38 -0500


On Wednesday, February 20, 2002, at 10:28 PM, richard@richardgordon.net (Richard Gordon) wrote:

>At 12:25 PM +1100 2/21/02, Adam Eijdenberg wrote:
>>Ben,
>>
>>A while back I got sick of this problem too, so I wrote a some 
>>simple C code to accomplish it. Since it is short I'll place it 
>>below:
>
>Maybe I misunderstood the question, but it looks like you guys are 
>working too hard....

[snip Richard's python script]

As a firm believer of giving back to the community, here are my
modifications to Richard's script.

	#1) Allows user to specify what type (pc, mac, unix) of lineendings
		they want
	
	#2) Got it to work under MacPython and UnixPython
	
	#3) More detailed output to user
	
	#4) Removed time logging stuff... couldn't get it to work under my
		UnixPython for some reason :-(
	
	#5) Handles .DS_Store files better (by skipping them)
	

Hope this helps someone,
-Ryan Wilcox
	
--------

#!/usr/bin/env python


#created by Richard Gordon
#posted to PythonMac-SIG Feb 20, 2002
#modified by WD-rpw Feb 20, 2002

#call it by [name] lineendingtype folder
#eg: switchendings pc ~/Desktop/temp/

import sys, os

fcount = 0

def strip(f, tp):
	global fcount
	infh = open(f, 'rb').read()
	outfh = open(f, 'wb')
	
	if infh.find('\r\n') != -1:
		if (tp == "mac"):
			outfh.write(infh.replace('\n',''))
			print "     translated from pc to mac"
		else: 
			if (tp == "unix"):
				outfh.write(infh.replace('\r',''))
				print "     translated from pc to unix"
	
	elif infh.find('\n') != -1:
		if (tp == "mac"):
			outfh.write(infh.replace('\n','\r'))
			print "     translated from unix to mac"
		elif (tp == "pc"):
			outfh.write(infh.replace('\n','\r\n'))
			print "     translated from unix to pc"
			
	elif infh.find('\r') != -1:
		if (tp == "unix"):
			outfh.write(infh.replace('\r','\n'))
			print "     translated from mac to unix"
		elif (tp == "pc"):
			outfh.write(infh.replace('\r','\r\n'))
			print "     translated from mac to pc"
	else: pass
	outfh.close()
	fcount = fcount + 1
	return

def run(d,tp):
	names = os.listdir(d)
	for name in names:
		f = d + name
		if os.path.isfile(f):
			if os.path.splitext(f)[1]!='.DS_Store':
				print "processing: " + name
				strip(f, tp)
		else: run(f, tp)

if not sys.argv[1:]:
	#we're on a mac now, baby
	import macfs, EasyDialogs
	from time import time
	fss, ok = macfs.GetDirectory('Folder to search:')
	if not ok:
		sys.exit(0)
	targetplatform = EasyDialogs.AskString\
		("convert line endings to: pc, mac, unix", "pc")
	run(fss.as_pathname(), targetplatform)
else:
	targetplatform = sys.argv[1]
	fss = sys.argv[2:]
	for arg in fss:
		run(arg, targetplatform)

print "Changed %d files" % (fcount)
print "done"