[Tutor] CSV Module , Kindly treat my last question with same subject as cancelled
Manprit Singh
manpritsinghece at gmail.com
Sat Sep 26 10:19:54 EDT 2020
Dear sir ,
Consider that a csv file named some.csv is saved in my PC . The contents
that are present in the csv file are as follows :
1,Andy,Science
2,Robin,Arts
Now for appending 2 more rows to the csv file, if i write code like this as
written below, is it ok ?
tup1 = (("3", "Serena", "Arts",),
("4", "Villiams", "Commerce",),)
with open('some.csv', 'a', newline='') as f: 'a' for append mode
writer = csv.writer(f) # Writer
object
writer.writerows(tup1)
After executing this code, the two rows got appended , as shown below,
which is the right answer
1,Andy,Science
2,Robin,Arts
3,Serena,Arts
4,Villiams,Commerce
Now coming to the main question . if i want these four rows in the form of
nested list as shown below :
[['1', 'Andy', 'Science'],
['2', 'Robin', 'Arts'],
['3', 'Serena', 'Arts'],
['4', 'Villiams', 'Commerce']]
The below written code is an efficient implementation for the output shown
above ?
l = []
with open('some.csv', newline='') as f:
reader = csv.reader(f) # Reader object
for row in reader:
l.append(row)
print(l)
Or this task can be achieved efficiently with another method ?
Regards
Manprit Singh
Or
More information about the Tutor
mailing list