Last active
March 4, 2024 02:17
-
-
Save devstar0209/c8ff6cd7412c644271f65bebffd5229c to your computer and use it in GitHub Desktop.
Read CSV file in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Open the CSV file using csv lib | |
import csv | |
file = open('Salary_Data.csv') | |
csvreader = csv.reader(file) | |
header = [] | |
header = next(csvreader) | |
header ## print header | |
rows = [] | |
for row in csvreader: | |
rows.append(row) | |
rows ## Print rows | |
# Open the CSV file using readlines() | |
with open('file.csv', 'r') as file: | |
## Read all lines from the file | |
lines = file.readlines() | |
header = lines[:1] | |
rows = lines[1:] | |
## Iterate over each line | |
for line in lines: | |
## Split the line into fields using comma as the delimiter | |
fields = line.strip().split(',') | |
## Print each field | |
print(fields) | |
# Open the CSV file using pandas | |
import pandas as pd | |
data= pd.read_csv("Salary_Data.csv") | |
data ## Print data | |
data.columns ## Extract the field names | |
data.Salary ## Extract the rows. Assume it has a Salary field. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment