[Tutor] Terminating "\M" characters with regard to csv.DictWriter
Alex Kleider
alexkleider at gmail.com
Sun Aug 8 22:05:23 EDT 2021
Using the csv module's DictReader and DictWriter to update data in a file
one of my functions is as follows:
def dict_write(f, fieldnames, iterable):
"""
Writes all records received from <iterable> into a new csv
file named <f>. <fieldnames> defines the record keys.
Code writen in such a way that <iterable> could be
a generator function.
"""
with open(f, 'w', newline="") as outfile_obj:
print("Opening {} for output...".format(outfile_obj.name))
dict_writer = csv.DictWriter(outfile_obj, fieldnames)
dict_writer.writeheader()
for record in iterable:
dict_writer.writerow(record)
All works as I would like except that the newly generated csv file has a
'\M' at the end of each line. I only became aware of this when doing a
diff between the original file and the one produced by my function. When
examining the files using vim (my text editor of choice) they look the same
(except for the changes I meant to make) so things seem to be working fine
and the system doesn't seem to mind.
Should I be setting the named 'newline' parameter to something other than
an empty string? From where do the '\M' characters come??? I'd very much
like to be able to use the 'diff' command to check if the correct changes
are being made but at present, diff marks every line as being different!
TIA
Alex Kleider
(Using python 7 on Debian GNU/Linux)
More information about the Tutor
mailing list