Read a CSV into list of lists in Python - GeeksforGeeks
文章推薦指數: 80 %
In this article, we are going to see how to read CSV files into a list of lists in Python. Method 1: Using CSV module. We can read the CSV ... Skiptocontent CoursesGeekWeek2022ForWorkingProfessionalsDSAClasses(Live)SystemDesign(Live)JavaBackendDeveloper(Live)FullStack(Live)ExploreMoreLiveCoursesDSA(Self-Paced)SDETheory(Self-Paced)AllDevelopmentCourses(Self-Paced)ExploreMoreSelf-PacedCoursesForStudentsCompetitiveProgramming(Live)GATECourse2023(Live)DataScience(Live)ExploreMoreLiveCoursesDSA(Self-Paced)CIP(Self-Paced)JAVA/Python/C++(Self-Paced)ExploreMoreSelf-PacedCoursesSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#SQLScalaPerlGoLanguageKotlinWebDevelopmentHTMLCSSJavaScriptPHPCSSFrameworksBootstrapTailwindCSSFoundationCSSMaterializeCSSBulmaPureCSSPrimerCSSBlazeUISemanticUIJavaScriptFrameworksAngularJSNodeJSJavaScriptLibrariesjQueryReactJSML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialGFGSheetsWebDevCheatSheetsHTMLCheatSheetCSSCheatSheetJSCheatSheetjQueryCheatSheetCompany-WiseSDESheetsFacebookSDESheetAmazonSDESheetAppleSDESheetNetflixSDESheetGoogleSDESheetWiproCodingSheetInfosysCodingSheetTCSCodingSheetCognizantCodingSheetHCLCodingSheetDSASheetsSDESheetFAANGCodingSheetLoveBabbarSheetMassRecruiterSheetProduct-BasedCodingSheetCompany-WisePreparationSheetArraySheetStringSheetTreeSheetGraphSheetDPSheetSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesBusinessStudies(Class11th)BusinessStudies(Class12th)CSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersUPSCGeographyNotesHistoryNotesScience&Tech.NotesEthicsNotesPolityNotesEconomicsNotesUPSCPreviousYearPapersSSCCGLSSCCGLSyllabusGeneralStudiesEnglishReasoningSubjectwisePracticePapersPreviousYearPapersBankingExamsSBIClerkSBIClerkSyllabusGeneralAwarenessEnglishQuantitativeAptitudeReasoningAbilitySBIClerkPracticePapersSBIPOSBIPOSyllabusGeneralAwarenessEnglishQuantitativeAptitudeReasoningAbilityPreviousYearPapersSBIPOPracticePapersIBPSPOIBPSPO2022SyllabusEnglishNotesReasoningNotesPreviousYearPapersMockQuestionPapersIBPSClerkIBPSClerkSyllabusEnglishNotesPreviousYearPapersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblemsContests ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningJavaScriptSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionReadJSONfileusingPythonTakinginputinPythonHowtogetcolumnnamesinPandasdataframeReadafilelinebylineinPythonPythonDictionaryIterateoveralistinPythonPythonprogramtoconvertalisttostringReadingandWritingtotextfilesinPythonPythonString|replace()Enumerate()inPythonDifferentwaystocreatePandasDataframesum()functioninPythonPrintlistsinPython(5DifferentWays)isupper(),islower(),lower(),upper()inPythonandtheirapplicationsConvertintegertostringinPython*argsand**kwargsinPythonPython|GetalistasinputfromuserPythonListsPython|ProgramtoconvertStringtoaListPythonString|split()CreateaPandasDataFramefromListsfloor()andceil()functionPythonGraphPlottinginPython|Set1GETandPOSTrequestsusingPythonTakingmultipleinputsfromuserinPythonFindaverageofalistinpythonStackinPythonHowtoInstallPIPonWindows?AddingnewcolumntoexistingDataFrameinPandasPythonmap()functionReadJSONfileusingPythonTakinginputinPythonHowtogetcolumnnamesinPandasdataframeReadafilelinebylineinPythonPythonDictionaryIterateoveralistinPythonPythonprogramtoconvertalisttostringReadingandWritingtotextfilesinPythonPythonString|replace()Enumerate()inPythonDifferentwaystocreatePandasDataframesum()functioninPythonPrintlistsinPython(5DifferentWays)isupper(),islower(),lower(),upper()inPythonandtheirapplicationsConvertintegertostringinPython*argsand**kwargsinPythonPython|GetalistasinputfromuserPythonListsPython|ProgramtoconvertStringtoaListPythonString|split()CreateaPandasDataFramefromListsfloor()andceil()functionPythonGraphPlottinginPython|Set1GETandPOSTrequestsusingPythonTakingmultipleinputsfromuserinPythonFindaverageofalistinpythonStackinPythonHowtoInstallPIPonWindows?ReadaCSVintolistoflistsinPythonViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: EasyLastUpdated: 08Apr,2022ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle Inthisarticle,wearegoingtoseehowtoreadCSVfilesintoalistoflistsinPython.Method1:UsingCSVmoduleWecanreadtheCSVfilesintodifferentdatastructureslikealist,alistoftuples,oralistofdictionaries.WecanuseothermoduleslikepandaswhicharemostlyusedinMLapplicationsandcoverscenariosforimportingCSVcontentstolistwithorwithoutheaders.Example1:Inthisexample,wearereadingaCSVfileandconvertingthestringintothelist. Python3importcsv withopen('sample.csv','r')asread_obj: #Returnareaderobjectwhichwill #iterateoverlinesinthegivencsvfile csv_reader=csv.reader(read_obj) #convertstringtolist list_of_csv=list(csv_reader) print(list_of_csv)Output:[[‘JAN’,34,360,417],[‘FEB’,31,342,391],[‘MAR’,36,406,419],[‘APR’,34,396,461], [‘MAY’,36,420,472],[‘JUN’,43,472,535],[‘JUL’,49,548,622],[‘AUG’,50,559,606], [‘SEP’,40,463,508],[‘OCT’,35,407,461],[‘NOV’,31,362,390],[‘DEC’,33,405,432]]Example2:Inthisexample,wearereadingaCSVfileanditeratingoverlinesinthegivenCSV. Python3importcsv withopen('example.csv')ascsvfile: #Returnareaderobjectwhichwill #iterateoverlinesinthegivencsvfile. readCSV=csv.reader(csvfile,delimiter=',') forrowinreadCSV: print(row) print(row[0]) print(row[0],row[1],row[2],) print("\n")Output: Method2:UsingPandasYoucanusethepandaslibraryforthiswhichhasaninbuiltmethodtoconvertvaluestoalist.Pandas.valuespropertyisusedtogetanumpy.arrayandthenusethetolist()functiontoconvertthatarraytolist.Note:FormoreinformationreferReadCSVIntoListUsingPandasPython3#app.py importpandasaspd #CreatingDictionarydict={ 'series':['Friends','MoneyHeist','Marvel'], 'episodes':[200,50,45], 'actors':['DavidCrane','Alvaro','StanLee']} #CreatingDataframedf=pd.DataFrame(dict)print(df)Output: MyPersonalNotes arrow_drop_upSave LikePreviousDifferencebetweenTensorandVariableinPytorchNext DivideoneHermiteseriesbyanotherinPythonusingNumPyRecommendedArticlesPage:22,Jan2023,Feb2103,Mar2125,Mar2109,Sep2106,May2123,Feb2103,Jul1823,Jan1906,Jul2003,Mar2116,Apr2116,Dec2113,Aug2010,Apr2016,Apr1901,Feb2116,Dec2107,May1930,Apr2028,Apr2122,Sep2102,Apr2027,Dec18ArticleContributedBy:ayushcoding100@ayushcoding100VotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertArticleTags:Pickedpython-csvPython-pandasPythonPracticeTags:pythonReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register
延伸文章資訊
- 1Python - Read CSV Columns Into List - GeeksforGeeks
In this method we will import the csv library and open the file in reading mode, then we will use...
- 2Python: Read CSV into a list of lists or tuples or dictionaries
We opened the csv file in read mode and then passed the file object to csv.DictReader() function....
- 3Read CSV to List in Python | Delft Stack
Python has a built-in module named CSV , which has a reader class to read the contents of a CSV f...
- 4Read 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...
- 5Reading Rows from a CSV File in Python - GeeksforGeeks