[Tutor] CSV Module
Manprit Singh
manpritsinghece at gmail.com
Sat Sep 26 01:18:12 EDT 2020
Dear Sir,
Consider a tuple (more precisely a nested tuple)as given below :
tup = (("1", "Andy", "Science",),
("2", "Robin", "Arts",), )
First of all i just need to know , if i maintain a habit to include a comma
even after the last element of tuple and list . As you can see I have
placed a comma just after "Science" and "Arts" as well as after the two
tuples ("1", "Andy", "Science",) and
("2", "Robin", "Arts",) . Is it a good habit ? I read somewhere that it is
better to write lists and tuples in this way . Need your comments.
Secondarily If i have to write a code to save the elements of the tuple
given above in a CSV file . In the first row i have to save "1", "Andy",
"Science" and in the second row i have to save "2", "Robin", "Arts".
import csv
with open('some.csv', 'w', newline='') as f:
writer = csv.writer(f) # Writer object
writer.writerows(tup) # Can write more than one
row
This will write the two rows in a file name "some.csv". Need your comments
about the above written code .
Another Question is now if i have to read the same csv, What about the
below written code. Need your humble comments
with open('some.csv', newline='') as f:
reader = csv.reader(f) # Reader object
for row in reader:
print(row) # Prints each row
Coming to the main point now :
The code written just above closes the file at the point when all rows are
printed, and once the file is closed you can not again access the same file
without repeating the same process . Now if i have to access this csv file
lots of time in a single program , Repeating the same above written process
again and again is the only way ? Can i assign this CSV file to a variable
so that i can use this csv file number of times in a programme ?Need your
humble comments in this regard
Regards
Manprit Singh
More information about the Tutor
mailing list