I have a csv file I made some calculation with code function on it. and requesting output is okay write now.
my question is:
should I write the close() at the end of the code? what would be difference when I write that line or I did not write it?
for example:
with open('grades.csv', 'w', newline='') as output_file_name:
writer = csv.writer(output_file_name)
writer.writerows(data)
output_file_name.close()
this (i.e. using
with
) is an example of so called
context manager
. When using context manager you don't need to close the file - it will close it for you.
Just
with open('grades.csv', 'w', newline='') as output_file_name:
writer = csv.writer(output_file_name)
writer.writerows(data)
is enough
thanks.
also I have another problem in my csv output file.
on writing process the code add some empty line at the end of csv file.
here is a sample of output:
Quote:1-peter,11.285714285714286
2-edmond,9.75
3-
I have numbered the line just to clarify my question, the third line is unnecessary.
check your data
- you will see the last element is empty
sorry, I didn't read carefully that the line numbers are just here, not in the file.
you got empty line, because every line that you write has a newline char at the end
from the docs for
csvwriter.writerows:
Quote:Write all elements in rows (an iterable of row objects as described above) to the writer’s file object, formatted according to the current dialect.
and the
default dialect lineterminator is '\r\n'
so it means in any way I will print a new line with this code on my csv file?
unless you write some weird code to handle line endings the way you want
it homework I should use csv in python to reach the preferred results.
hopefully you answer my question sooner that my mentor.
I have a five different function that check the first csv file and rewrite the results on it as an output_file_name.
I have two problem until now.
1-how to remove that empty line in the writing process.
2- how to check the every steps on my computer before sending it.