How to Upload Csv in Python and Manipulate
Introduction to Python Import CSV
In this article, nosotros will see CSV is elaborated as comma-separated-values which is used to store tabular data or spreadsheet file format, which uses comma as delimiter or separator, and such files are known as CSV files. In Python, to parse or work with such CSV files, we need to import the CSV module, an inbuilt module. To exercise this, nosotros need to use the "import" keyword before "csv" to support CSV files or to parse CSV files in python. This csv module in Python is used to read or write or handle CSV files; to read or write such files, we demand to loop through the CSV file rows.
Working of CSV Module in Python
In this article, we will see how to import the csv module in Python. In Python, csv is an inbuilt module used to support CSV files, such every bit reading CSV files. Therefore to extract data from a CSV file, nosotros have to loop through rows, and we also accept to utilise separate methods to extract data from each cavalcade which are separated by commas.
Now let u.s. come across how to import the csv module.
Import CSV
This statement is used for importing a csv module that is used for parsing tabular like data structure such equally data in excel format, and these files are saved in .csv extension; this csv modules provide diverse classes for reading and writing data to CSV files. Now we will come across diverse csv module functions and classes in the below section.
Examples to Implement Python Import CSV
Below are the examples of Python Import CSV:
Instance #i – Reading CSV File using CSV Module Office as csv.reader()
This function is used to excerpt data from CSV files to read and print the output screen data. To do this, we demand to create a reader object; and then, the function will read each line of the CSV file and make the list of columns and print it. We can read CSV files that are separated from whatsoever other delimiter other than comma-separated files.
Now will meet how to read CSV file and is demonstrated in the below example:
Code:
import csv impress("Plan to demonstrate csv.reader() function:") print("\northward") c = open('visitor.csv','r') print("The csv file is opened for reading:") print("\n") o = csv.reader(c) print("The contents of the above file is every bit follows:") for r in o: print (r) c.close()
Output:
Explanation: In the above program, we can encounter we are reading file company.csv, which is already present in the current directory where the python software is present using an open() function with read manner 'r'. and the output displays the content of the file. This function gives No such file or directory as an fault message if the file does not be.
Example #2 – Writing to the File using csv.writer()
This function is used to write the data to the file. This function can also be used to create a new file and open it in the write mode 'due west'. Allow us demonstrate this function in the below example.
Code:
import csv print("Program to demonstrate csv.writer() office") impress("\due north") p_details =[('grade','fees','place'),('Python',22000,'Pune'),('Android',11000,'Assam'),('Java',30000,'Delhi')] c = open('programs.csv','w') print("File is opened for writing:") o = csv.writer(c) for p in p_details: o.writerow(p) c.shut()
Output:
Explanation: In the above programme, we can come across nosotros are writing details of programming courses, and we have opened a file named 'programs.csv' in write style 'w', which outset creates a file, and then the details are written to the file. And in the output screen, we can meet information technology will print saying the file is opened for writing, and when nosotros open up the file, we tin see information technology in CSV format as shown in the above screenshot, where each data is written in separate columns and row. Note that CSV uses excel as the default output to display the CSV file.
We will now see classes provided by the Python csv module for reading from and writing to a CSV file. DictReader and DictWriter are like to reader and writer functions equally in the higher up section. But these classes apply dictionary objects to read and write CSV files. Now will see these classes in the below department.
Example #3 – DictReader
This grade uses a dictionary object which is created for mapping the data to read it to the dictionary whose cardinal is given by field names, merely if the keys are non defined or declared, then by default, it will accept first row information as keys of the dictionary. Permit us demonstrate in the below example.
Lawmaking:
import csv impress("Program to demonstrate DictReader() class") print("\n") with open('company.csv') as c: r = csv.DictReader(c) for row in r: impress(row['Name'], row['Age'])
Output:
Explanation: In the above program, nosotros can see that nosotros are using DictReader() function, which will read the file company.csv, and this volition print but those which keys are specified, such as "Name" and "Age" are the keys of the dictionary which is a company.csv file content. And then in the above screenshot of output, only the contents of "Proper noun" and "age" are displayed.
Example #four – DictWriter
This class is also similar to the writer() function. In this form, this also specifies the keys of the lexicon through "fieldnames" as these keys are optional in the above DictReader, but keys are must exist specified to avoid ambivalence when writing the data to the CSV file.
Allow the states demonstrate in the below example.
Code:
import csv print("Program to demonstarte DictWriter() grade") print("\n") with open('Game.csv', 'w') as file: columnnames = ['Game_name', 'No_of_players'] writer = csv.DictWriter(file, fieldnames=columnnames) author.writeheader() author.writerow({'Game_name': 'Cricket', 'No_of_players': 12}) writer.writerow({'Game_name': 'Football game', 'No_of_players': xi}) writer.writerow({'Game_name': 'Hockey', 'No_of_players': xi})
Output:
Explanation: In the above programme, we tin encounter nosotros have created a new file "Game.csv" in write way "westward" by using an open up() part, and so we utilise DictWriter() to write the data to the file, and here nosotros mention the cavalcade names as field names which are the keys for the dictionary created. In the above output, we can encounter how the file is created and the data is written to it.
Decision
This article concludes that the CSV module in Python is used to piece of work with CSV(comma separated values) files. CSV modules are also used in many applications in the information science subjects using the pandas concept in Python. This article saw how to read from and write to CSV files using this csv module. In this, nosotros also saw a few CSV functions such every bit reader() and author() functions and classes such as DictReader() and DictWriter(), which are created equally dictionaries forth with keys as field names.
Recommended Articles
This is a guide to Python Import CSV. Here nosotros discuss a brief overview of Python Import CSV and its Examples forth with its Code Implementation. You lot can also go through our other suggested articles to learn more –
- Advantages of Programming in Python
- What is Recursive Function in Python?
- Introduction to Python Range Function
- Top seven Methods of Python Ready Function
Source: https://www.educba.com/python-import-csv/
0 Response to "How to Upload Csv in Python and Manipulate"
Post a Comment