1.Import and Export(How to read csv file using manualvfunction)

#!/usr/bin/env python
# coding: utf-8

# In[5]:



# Week1: Write a python program to import and export data from/to CSV file
#########################################################################
## (1) How to Read CSV File using Manual Function
import pandas as pd

def load_csv(filepath):
    data = []
    col = []
    checkcol = False
    with open(filepath) as f:
        for val in f.readlines():
            val = val.strip()
            val = val.split(',')
            if checkcol is False:
                col = val
                checkcol = True
            else:
                data.append(val)
    df = pd.DataFrame(data=data, columns=col)
    return df

# Replace 'yourfile.csv' with the actual file path
myfile = r"C:\Users\91887\OneDrive\Desktop\Machine_Learning\Sales_Records.csv"
myData = load_csv(myfile)
print(myData.head())


# In[ ]:




# In[6]:


## (2) How to Read CSV File in python Using Pandas?
df = pd.read_csv(myfile)
#df.head()
df[1:5]


# In[8]:


X=df.iloc[:,:-1]
print (X)


# In[9]:


y=df.iloc[:,-1:]
print (y)


# In[10]:


# Extract Columns
df.columns


# In[11]:


# Extract Rows
df.Region


# In[12]:


df['Total Cost']


# In[18]:


## (3) How to Read CSV File in Python using csv.reader()
import csv
file = open(myfile)
csvreader = csv.reader(file)
header = next(csvreader)
rows = []
for row in csvreader:
    rows.append(row)
print(header)
print(rows)
file.close()


# In[20]:


## (4) How to read CSV Files in Python Using .readlines()?
with open(myfile) as file:
    content = file.readlines()
header = content[:1]
rows = content[1:]
print(header)
print(rows)


# In[30]:


## (5) Write CSV file Using csv.writer
import csv
header = ['Name', 'M1 Score', 'M2 Score']
data = [['Alex', 62, 80], ['Brad', 45, 56], ['Joey', 85, 98]]
filename = 'Students_Data.csv'
with open(filename, 'w', newline="") as file:
    csvwriter = csv.writer(file) # 2. create a csvwriter object
    csvwriter.writerow(header) # 4. write the header
    csvwriter.writerows(data) # 5. write the rest of the data


# In[35]:


import json

# Opening JSON file using a context manager
with open(r"C:\Users\91887\OneDrive\Desktop\Machine_Learning\anscombe.json") as f:
    # returns JSON object as a dictionary
    data = json.load(f)
   
    # Iterating through the json list
    for i in data:
        print(i)
# Closing file
f.close()


# In[ ]:





Comments

Popular posts from this blog

How to became a junior Engineer

K Means_Clustering