Ich möchte ein Programm schreiben, sodass durch die Eingabe:
$ python convert_encoding.py in_dir/fileXY.txt latin-1 out_dir/fileXY.txt utf-8
ein Textfile von (zB) latin-1 nach (zB) utf-8 enkodiert werden.
Hierzu habe ich folgenden Code beisammen:
Code: Alles auswählen
import os
class Encoding():
def convert_encoding(infilename, from_enc, to_enc, eol=os.linesep,
outfilename=""):
def error_cleanup():
if hasattr(infilename, 'close'):
infilename.close()
if hasattr(outfilename, 'close'):
outfilename.close()
if os.path.isfile(outfilename) and os.path.isfile(infilename):
os.remove(outfilename)
warn("Processing %s ... " % infilename, nl=False)
if os.path.isfile(infilename):
#
# choose temp file
tempfilename = infilename + "." + to_enc
while os.path.isfile(tempfilename):
tempfilename = tempfilename + "x"
#
# open original file (infile) and tempfile (outfile)
infile = outfile = None
try:
infile = codecs.open(infilename, "rb", from_enc)
except Exception, details:
warn("Error opening %s: %s" % (infilename, details));
error_cleanup()
return None
try:
outfile = codecs.open(tempfilename, "wb", to_enc)
except Exception, details:
warn("Error opening %s: %s" % (tempfilename, details))
error_cleanup()
return None
#
# go through infile, convert, and write to outfile
try:
for line in infile:
try:
line = line.replace("\r\n", "\n") # win
line = line.replace("\n", eol)
outfile.write(line)
except Exception, details:
raise Exception, "Error writing to %s: %s" \
% (tempfilename, details);
except Exception, details:
warn("Error in I/O: %s" % details)
error_cleanup()
else:
#
# Finish up: overwrite original file with tempfile
try:
infile.close()
outfile.close()
shutil.copystat(infilename, tempfilename)
overwrite = False
if outfilename == "":
outfilename = infilename
overwrite = True
rename_file(tempfilename, outfilename, overwrite)
warn("%s was successfully converted from %s to %s" \
% (infilename, from_enc, to_enc))
warn("") # finish a block
except Exception, details:
warn("Renaming %s to %s FAILED. File was not converted: %s" \
% (tempfilename, infilename, details))
error_cleanup()
warn("") # finish a block
else:
warn("File '%s' does not exist\n" % file)
Zudem: Mit meinem Code kann ich das Programm nicht so aufrufen, wie das vorgegeben ist. Wie müsste ich ihn verändern, damit das möglich ist?
MfG und besten Dank, Marcel.