save csv python code example
Example 1: python save df to csv
df.to_csv(r'/directory/path/file_name.csv', index = False, header = True)
Example 2: code how pandas save csv file
df.to_csv('out.csv')
Example 3: create csv file python
# This action requires the 'csv' module
import csv
# The basic usage is to first define the rows of the csv file:
row_list = [["SN", "Name", "Contribution"],
[1, "Linus Torvalds", "Linux Kernel"],
[2, "Tim Berners-Lee", "World Wide Web"],
[3, "Guido van Rossum", "Python Programming"]]
# And then use the following to create the csv file:
with open('protagonist.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(row_list)
# This will create a csv file in the current directory
Example 4: how to write csv from a dataframe pythin
df.to_csv('file_name.csv')
Example 5: csv python write
import csv
with open('names.csv', 'w') as csvfile:
fieldnames = ['first_name', 'last_name']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
Example 6: read csv python
import pandas as pd
data = pd.read_csv("filename.csv")
data.head()