How To Read CSV to List in Python - Studytonight

文章推薦指數: 80 %
投票人數:10人

Example: Reading CSV to List in Python · It created a list of lists containing all rows of the CSV file and print that list of lists. · Here, in the first step, ... MastertheGoProgrammingLanguage(Golang)andGetjob-ready.🥳 🚀  BestDevOpsRoadmapforBeginners(inHindi).😍🤩  TheUltimateDSARoadmapfor2022.😍🤩  Signup/SignIn DarkModeOn/Off InteractiveLearning LearnHTML LearnCSS LearnJavaScript CLanguage CTutorial CPrograms(100+) CCompiler ExecuteCprogramsonline. C++Language C++Tutorial StandardTemplateLibrary C++Programs(100+) C++Compiler ExecuteC++programsonline. Python PythonTutorial PythonProjects PythonPrograms PythonHowTos NumpyModule MatplotlibModule TkinterModule NetworkProgrammingwithPython LearnWebScraping MoreinPython... PythonCompiler ExecutePythoncodeonline. Java CoreJavaTutorial JavaPrograms(100+) JavaCodeExamples(100+) Servlet JSP-JavaServerPages JavaTypeConversionExamples JavaWrapperClass SpringFramework Java11 MoreinJava... JavaCompiler ExecuteJavacodeonline. ComputerSci.(GATE) OperatingSystem ComputerArchitecture ComputerNetwork Database DBMS LearnSQL MongoDB PL/SQL PracticeSQL ExecuteSQLQueriesonline. MoreTutorials... Android Kotlin GameDevelopment GOLanguage GITGuide LinuxGuide Docker SpringBoot PHP HTMLTags(AtoZ) CSS JavaScript SASS/SCSS Tests MCQstotestyourknowledge. Forum Engagewiththecommunity. Compilers Compilerstoexecutecodeinbrowser. LearntoCode Library Tests Forum TechBlog Login Index Explore: TutorialsLibrary MCQTests Curious? LearnCoding! PythonBasics FloatRoundtoTwoDecimalsCheckifaVariableExistsCheckPythonVersionYieldkeywordinUpgradePythonPackagesGenerateRandomValueAssertinPythonUnderscoreinPythonConvertByteToHexCommentinPythonErrorHandlinginPythonNormalvsKeywordArgumentsScopeofvariableinIfStatementPythonOOPS CreateClassCreateanObjectStaticvsClassMethodFindAllSubClassesPassMethodasArgumentPythonString PrintColourfulTextStringSlicingRemovenumbersfromStringStringtoCharArrayRemovetrailingnewlinesCreateMultiLineStringConvertStringtoStringArrayConvertStringtoByteConvertBytetoStringRemoveSpacefromStringCounttheStringOccurrenceConvertStringtoUTF-8ReplaceStringMD5SumOfStringDecodeHTMLEntitiesPythonList ConvertListtoStringConcatenateListsFindAverageofaListFindMaxFromListListSubtractionCountUniqueValuesinListCreatingArrayCheckListSameElementsListstoDictionaryDel,RemoveandPopPermutationofListMergeTwoListsLongestStringinListPrintRandomfromListHowtoSliceHowtoaddListasArgumentDeleteFromListTupletoListReadListElementsRotateaListTwoListAdditionPythonTuple PassTupleasanArgumentHowtoAddPythonDate&Time CompareTwoDatesAddDaystoDateCurrentdateandtimeGetYearfromDatePythonExecutionTimeConvertSecondstoMinutesDatetoStringConvertDateTimetoSecondsGetMonthNamePythonSet JointwoSetsAddElementsintoSetDeleteElementsfromSetAccessSetElementsSetwithrangeCreateanImmutableSetAddListtoSetPythonDictionary FindKeyFromValueinDictionaryReverseDictionaryCheckValueExistsinDictionaryListofValueFromDictionaryPythonFileandI/O UnzipFileReadXMLfileinpythonReadCSVfileinPythonReadJSONFileCheckFileSizeListallfilesReadYAMLinPythonReadCSVToListAppendTextToaFileCheckFileExistinPythonFindfileswithCertainExtensionGetLastofPathReadFileFromLine2SearchandReplaceFileTextReadFirstLineGetTheHomeDirectorySearchandReplaceTextinFileCheckIfFileisEmptyPythonJSON PrintPrettyJSONConvertJSONtoDictionary ←PrevNext→HomePythonHowTosHowToReadCSVtoListinPythonHowToReadCSVtoListinPython Inthistutorial,wewilllearnhowtoreadCSVtolistinpython.First,let'sdiscusstheCSV. WhatisCSVFile? CSV(CommaSeparatedValues)isaplaintextfile.TheseCSVfilesareusedindifferentapplicationsforexchangingdatalikecontactmanagersanddatabases. TheseCSVfilesarealsocalledCommaDelimitedFilesorCharacterSeparatedValues. ThedifferentnamesaregiventoCSVfilessincewecanexportcomplexdatafromoneapplicationtoaCSVfileandthenwecanimportdatafromtheseCSVfiledataintoanotherapplication. ReadingCSVfilesintoListinPython. WecanreadtheCSVfilesintodifferentdatastructureslikealist,alistoftuples,oralistofdictionaries. WecanuseothermoduleslikepandaswhicharemostlyusedinMLapplicationsandcoverscenariosforimportingCSVcontentstolistwithorwithoutheaders. Example:ReadingCSVtoListinPython ThisisasampleCSVfilethatwillbeusedtoreadintoalist. Id,Name,Course,City,Session 1,Bheem,Python,India,Morning 2,Chutki,Python,London,Evening 3,Tom,Python,USA,Morning 4,Jerry,Python,Japan,Morning Nowwehavetoreadthisfileintoalistoflistsinpython. Initially,ImportCSVtoalistoflistsusingCSV.reader. Pythonhasabuilt-inCSVmodule,itwillhelptoreadthedatafromtheCSVfileusingareaderclass.i.e,fromCSVimportreader. importcsv withopen('students.csv','r')asread_obj:#readcsvfileasalistoflists csv_reader=csv.reader(read_obj)#passthefileobjecttoreader()togetthereaderobject list_of_rows=list(csv_reader)#Passreaderobjecttolist()togetalistoflists print(list_of_rows) [['Id','Name','Course','Country','Session'], ['1','Bheem','Python','India','Morning'], ['2','Chutki','Python','London','Evening'], ['3','Tom','Python','USA','Morning'], ['4','Jerry','Python','Japan','Morning']] ItcreatedalistoflistscontainingallrowsoftheCSVfileandprintthatlistoflists. Here,inthefirststep,thefileisreadtobeopen,soopenthefileinreadingmodeandlatertransferthatfileobjectintothefunctioncsv_reader(). Itwillresultinaniterator,whichcanbeusedtoiterateoverallthelinesoftheCSVfile. Wewanttheresultinlistformatsothelist()functionisusedtoreturntheresultinthelistofthelist. TheobtainedresultrowofCSVandeachiteminthelistrepresentsacell/columninthatrow. Example2:Selectionofdatabyusingrowandcolumnnumbers Byusingalistoflistscreatedabovewecanselectindividualdatabyusingrowandcolumnnumbers. row_number=2 col_number=1 value=list_of_rows[row_number-1][col_number-1] print('Valueinacellat2ndrowand1stcolumn:',value Valueinacellat2ndrowand1stcolumn:1 Example3:UsingPandastoreadCSV ThebelowexampleshowshowtoreadtheCSVfileintoalistwithouttheheaderbyusingthepandaslibrary. importpandasaspd df=pd.read_csv('students.csv',delimiter=',') list_of_rows=[list(row)forrowindf.values] print(list_of_rows) ['1','Bheem','Python','India','Morning'], ['2','Chutki','Python','London','Evening'], ['3','Tom','Python','USA','Morning'], ['4','Jerry','Python','Japan','Morning']] Here,first,uploadtheCSVfileintoadataframeusingread_csv(). Dataframevaluesreturnallrowsin2dNumpyformatexcludingtheheader. Thenweiteratedoverallrowsofthisobtainedresultusinglistcomprehensionandcreatedalistoflists. Example4:ReadCSVfilesintoalistoftuplesusingPython FirstuploaddatafromtheaboveCSVfilethatisStudent.csvintoalistoftuples,whereeachtupleinthelistrepresentsarowandeachdatainthetuplerepresentsacell. withopen('students.csv','r')asread_obj:#passthefileobjecttoreader()togetthereaderobject csv_reader=reader(read_obj)#Getallrowsofcsvfromcsv_readerobjectaslistoftuples list_of_tuples=list(map(tuple,csv_reader))#displayallrowsofcsv print(list_of_tuples) [('Id','Name','Course','Country','Session'), ('1','Bheem','Python','India','Morning'), ('2','Chutki','Python','London','Evening'), ('3','Tom','Python','USA','Morning'), (4','Jerry','Python','Japan','Morning')] Example5:ReadCSVintoalistofdictionariesusingPython ByusingtheDictReadermodule,wecanreadCSVintoalistofdictionaries. fromCSVimportDictReader#openfileinthereadmode withopen('students.csv','r')asread_obj:#passthefileobjecttoDictReader()togettheDictReaderobject dict_reader=DictReader(read_obj)#getalistofdictionariesfromdct_reader list_of_dict=list(dict_reader)#printlistofdicti.e.rows print(list_of_dict) [{‘Id’:'1',‘Name’:'Bheem',’Course’:'Python',’Country’:'India',‘Session’:'Morning'}, {‘Id’:2',‘Name’:'Chutki',’Course’:'Python',’Country’:'London',‘Session’:'Evening'}, {‘Id’:'3',‘Name’:'Tom',’Course’:'Python',’Country’:'USA',‘Session’:'Morning'}, {‘Id’:'4',‘Name’:'Jerry',’Course’:'Python',’Country’:'Japan',‘Session’:'Morning'}] Conclusion Inthistutorial,welearnedhowtoreadaCSVfiletoListfromdifferentapproaches. ←ReadYAMLinPython←PREVAppendTextToaFile→NEXT→  MCQTests PrepareforyournexttechnicalInterview.Weaddnewtestseveryweek. Explore



請為這篇文章評分?