How to Read Csvfile Without /n Python
Intro: In this commodity, I volition walk y'all through the different ways of reading and writing CSV files in Python.
Table of Contents:
- What is a CSV?
- Reading a CSV
- Writing to a CSV
1. What is a CSV?
CSV stands for "Comma Separated Values." It is the simplest form of storing data in tabular form as manifestly text. It is of import to know to work with CSV because we mostly rely on CSV data in our day-to-day lives every bit data scientists.
Structure of CSV:
Nosotros have a file named "Salary_Data.csv." The first line of a CSV file is the header and contains the names of the fields/features.
After the header, each line of the file is an observation/a record. The values of a record are separated by "comma."
two. Reading a CSV
CSV files tin be handled in multiple means in Python.
2.1 Using csv.reader
Reading a CSV using Python's inbuilt module chosen csv using csv.reader object.
Steps to read a CSV file:
i. Import the csv library
import csv
ii. Open the CSV file
The .open() method in python is used to open files and return a file object.
file = open('Salary_Data.csv') type(file)
The type of file is "_io.TextIOWrapper" which is a file object that is returned by the open() method.
iii. Use the csv.reader object to read the CSV file
csvreader = csv.reader(file)
iv. Extract the field names
Create an empty list chosen header. Use the next() method to obtain the header.
The .next() method returns the current row and moves to the side by side row.
The outset time you run next() it returns the header and the side by side time you run it returns the first record and so on.
header = [] header = next(csvreader) header
5. Extract the rows/records
Create an empty list chosen rows and iterate through the csvreader object and append each row to the rows list.
rows = [] for row in csvreader: rows.append(row) rows
six. Close the file
.close() method is used to close the opened file. Once it is airtight, nosotros cannot perform whatsoever operations on information technology.
file.close()
Complete Code:
import csv file = open("Salary_Data.csv") csvreader = csv.reader(file) header = side by side(csvreader) print(header) rows = [] for row in csvreader: rows.append(row) print(rows) file.close()
Naturally, we might forget to shut an open file. To avoid that we can apply the with()statement to automatically release the resources. In unproblematic terms, there is no need to call the .close() method if we are using with() statement.
Implementing the in a higher place code using with() statement:
Syntax: with open(filename, manner) every bit alias_filename:
Modes:
'r' – to read an existing file,
'w' – to create a new file if the given file doesn't exist and write to it,
'a' – to append to existing file content,
'+' – to create a new file for reading and writing
import csv rows = [] with open("Salary_Data.csv", 'r) as file: csvreader = csv.reader(file) header = next(csvreader) for row in csvreader: rows.append(row) impress(header) impress(rows)
2.2 Using .readlines()
At present the question is – "Is it possible to fetch the header, rows using but open() and with() statements and without the csv library?" Allow's see…
.readlines() method is the reply. It returns all the lines in a file as a list. Each item of the listing is a row of our CSV file.
The first row of the file.readlines() is the header and the rest of them are the records.
with open('Salary_Data.csv') as file: content = file.readlines() header = content[:one] rows = content[one:] print(header) print(rows)
**The 'n' from the output can be removed using .strip() method.
What if we have a huge dataset with hundreds of features and thousands of records. Would it be possible to handle lists??
Here comes the pandas library into the moving-picture show.
2.3 Using pandas
Steps of reading CSV files using pandas
1. Import pandas library
import pandas every bit pd
2. Load CSV files to pandas using read_csv()
Basic Syntax: pandas.read_csv(filename, delimiter=',')
information= pd.read_csv("Salary_Data.csv") information
3. Extract the field names
.columns is used to obtain the header/field names.
data.columns
four. Extract the rows
All the data of a data frame can be accessed using the field names.
information.Salary
3. Writing to a CSV file
Nosotros tin can write to a CSV file in multiple ways.
three.ane Using csv.writer
Let's assume we are recording 3 Students data(Proper noun, M1 Score, M2 Score)
header = ['Name', 'M1 Score', 'M2 Score'] data = [['Alex', 62, 80], ['Brad', 45, 56], ['Joey', 85, 98]]
Steps of writing to a CSV file:
1. Import csv library
import csv
2. Define a filename and Open the file using open()
3. Create a csvwriter object using csv.writer()
4. Write the header
5. Write the rest of the data
code for steps two-5
filename = 'Students_Data.csv' with open up(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 information
Below is how our CSV file looks.
three.two Using .writelines()
Iterate through each listing and convert the list elements to a string and write to the csv file.
header = ['Name', 'M1 Score', 'M2 Score'] information = [['Alex', 62, 80], ['Brad', 45, 56], ['Joey', 85, 98]] filename = 'Student_scores.csv' with open(filename, 'w') as file: for header in header: file.write(str(header)+', ') file.write('north') for row in information: for x in row: file.write(str(x)+', ') file.write('north')
3.iii. Using pandas
Steps to writing to a CSV using pandas
ane. Import pandas library
import pandas every bit pd
ii. Create a pandas dataframe using pd.DataFrame
Syntax: pd.DataFrame(information, columns)
The information parameter takes the records/observations and the columns parameter takes the columns/field names.
header = ['Name', 'M1 Score', 'M2 Score'] data = [['Alex', 62, lxxx], ['Brad', 45, 56], ['Joey', 85, 98]] data = pd.DataFrame(data, columns=header)
iii. Write to a CSV file using to_csv()
Syntax: DataFrame.to_csv(filename, sep=',', index=False)
**separator is ',' by default.
alphabetize=Fake to remove the alphabetize numbers.
data.to_csv('Stu_data.csv', index=False)
Beneath is how our CSV looks like
Cease Notes:
Thank you for reading till the conclusion. By the terminate of this article, we are familiar with different ways of handling CSV files in Python.
I promise this commodity is informative. Feel free to share it with your study buddies.
References:
Check out the complete code from the GitHub repo.
Other Blog Posts by me
Feel complimentary to cheque out my other blog posts from my Analytics Vidhya Profile.
Yous can notice me on LinkedIn, Twitter in case you would want to connect. I would be glad to connect with you.
For immediate exchange of thoughts, please write to me at harikabont[email protected].
mixonvadvapegul1994.blogspot.com
Source: https://www.analyticsvidhya.com/blog/2021/08/python-tutorial-working-with-csv-file-for-data-science/
0 Response to "How to Read Csvfile Without /n Python"
Post a Comment