Read CSV to List in Python | Delft Stack
文章推薦指數: 80 %
Python has a built-in module named CSV , which has a reader class to read the contents of a CSV file. The example code to read the CSV to a list ... PythonHow-To'sCheckOperatingSystemUsingPythonConditionalAssignmentOperatorinPythonPlayMp3FileUsingPythonRemoveCommasFromStringinPythonConvertBytestoIntinPython2.7and3.xConvertInttoBytesinPython2andPython3GetandIncreasetheMaximumRecursionDepthinPythonCreateandActivateaPythonVirtualEnvironmentreportthisad reportthisadHowToPythonHow-To'sReadCSVtoListinPythonReadCSVIntoaListinPythonUsingcsv.readerReadCSVIntoaListinPythonUsingcsv.readerWithOtherDelimitersThisarticleintroduceshowtoreadCSVtolistinPython.Let’ssupposewehaveaCSVfileEmployees.csvwiththefollowingcontentinit,IdNameDepartmentemailSalary1SamHumanResourcesam@[email protected]@gmail.com70K4MikeAccountsmike@gmail.com35KIfyouopenthisfileusingsometexteditor,itscontentshouldlooklikethis.Id,Name,Department,email,Salary 1,Sam,HumanResource,[email protected],65K 2,John,Management,[email protected],58K 3,Tonny,IT,[email protected],70K 4,Mike,Accounts,[email protected],35K NowwewillimporttheabovedataofthisCSVfileintoaPythonlist.ReadCSVIntoaListinPythonUsingcsv.readerPythonhasabuilt-inmodulenamedCSV,whichhasareaderclasstoreadthecontentsofaCSVfile.TheexamplecodetoreadtheCSVtoalistinPythonisasfollows.fromcsvimportreader withopen('Employees.csv','r')ascsv_file: csv_reader=reader(csv_file) #Passingthecav_readerobjecttolist()togetalistoflists list_of_rows=list(csv_reader) print(list_of_rows) csv_reader=reader(csv_file)passesthefileojbectcsv_filetothecsv.reader()functionandgetsthereaderobject.Itreturnsaniterator,whichisusedtoiterateoverallthelinesoftheCSVfile.list_of_rows=list(csv_reader)convertsthecsv.readerobjecttoalistoflists,whereeachelementofthelistmeansarowofCSV,andeachiteminthelistelementrepresentsacellorcolumninarow.Output:[['Id','Name','Company','email','Salary'], ['1','Sam','HumanResource','[email protected]','65K'], ['2','John','Management','[email protected]','58K'], ['3','Tonny','IT','[email protected]','70K'], ['4','Mike','Accounts','[email protected]','35K']] ReadCSVIntoaListinPythonUsingcsv.readerWithOtherDelimitersThecsv.readerfunctionalsoprovidesanoptiontoreadthetextfilesinwhichvaluesareseparatedbysomeothercharacterratherthanacomma.Forexample,thedelimitercouldbeataborwhitespace.Toreadsuchfiles,weneedtopassanextraparameterdelimitertothereaderfunction.Seetheexamplebelow.IfwehaveafileEmployees_TSV.csvwiththesamecontentasinEmployees.csvbutseparatedbytabratherthanacomma.fromcsvimportreader withopen('Employees_TSV.csv','r')ascsv_file: csv_reader=reader(csv_file,delimiter='\t') list_of_rows=list(csv_reader) print(list_of_rows) Wereaddatafromatab-separatedvaluesfileintheabovecode.delimiter='\t'specifiesthatthedelimiterintheCSVfileisthetab.Theoutputofthiscodeisthesameastheabove.RelatedArticle-PythonListConvertaDictionarytoaListinPythonRemoveAlltheOccurrencesofanElementFromaListinPythonRemoveDuplicatesFromListinPythonGettheAverageofaListinPythonRelatedArticle-PythonCSVConvertaDictionarytoaListinPythonRemoveAlltheOccurrencesofanElementFromaListinPythonRemoveDuplicatesFromListinPythonGettheAverageofaListinPythonRemovetheLastCharacterFromStringinPythonReverseaListinPythonx
延伸文章資訊
- 1Reading Rows from a CSV File in Python - GeeksforGeeks
- 2How to read a `csv` file into a list in Python - Adam Smith
Call open(filepath, mode) with a .csv file path as filepath and "r" as mode to return a file obje...
- 3How to read specific column from CSV file in Python - Adam Smith
- 4How to Import CSV to List Python - Linux Hint
Line 1: We import the CSV module. Line 2 to 4: We open the sample.csv file in the read mode 'r'. ...
- 5Read a CSV into list of lists in Python - GeeksforGeeks
In this article, we are going to see how to read CSV files into a list of lists in Python. Method...