Computer Science
Write a Python program to write a nested Python list to a csv file in one go. After writing the CSV file read the CSV file and display the content.
Answer
import csv
def write_nested_list(data, file_name):
with open(file_name, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
def read_csv(file_name):
with open(file_name, 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
nested_list = [['Name', 'Age', 'Gender'],
['Prateek', '14', 'Male'],
['Ananya', '24', 'Female'],
['Aryan', '44', 'Male']]
write_nested_list(nested_list, 'output.csv')
print("Content of 'output.csv':")
read_csv('output.csv')
Output
['Name', 'Age', 'Gender']
['Prateek', '14', 'Male']
['Ananya', '24', 'Female']
['Aryan', '44', 'Male']
Related Questions
Write a function Show_words() in python to read the content of a text file 'NOTES.TXT' and display only such lines of the file which have exactly 5 words in them.
Example, if the file contains :
This is a sample file.
The file contains many sentences.
But need only sentences which have only 5 words.Then the function should display the output as :
This is a sample file.
The file contains many sentences.Write a Python program to read a given CSV file having tab delimiter.
Write a function that reads a csv file and creates another csv file with the same content, but with a different delimiter.
Write a function that reads a csv file and creates another csv file with the same content except the lines beginning with 'check'.