Reading Rows from a CSV File in Python - GeeksforGeeks

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

Using reader we can iterate between rows of a CSV file as a list of values. It iterates over all rows in a CSV file and fetches data in each row ... 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 HomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningJavaScriptSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesGeeksforGeeksSchoolLibrariesinPythonHowtoConnectPythonwithSQLDatabase?EquationofaLinein3DDataCommunication-Definition,Components,Types,ChannelsDomainconstraintsinDBMSDegreeofRelationsinDBMSSQLHAVINGClausewithExamplesLogicGates-Definition,Types,UsesDifferencebetweenwrite()andwritelines()functioninPythonAlgebraSortingAlgorithmsinPythonWhatisanIPAddress?StatisticsGraphicalSolutionofLinearProgrammingProblemsCardinalityinDBMSSQLUSEDatabaseStatementShortestDistanceBetweenTwoLinesin3DSpace|Class12MathsCalculusBayes'TheoremClass12NCERTSolutions-MathematicsPartI-Chapter2InverseTrigonometricFunctions-Exercise2.1LinearProgrammingDotandCrossProductsonVectorsp-nJunctionDiode-Definition,Formation,Characteristics,ApplicationsInvertibleFunctionsTorqueonanElectricDipoleinUniformElectricFieldPropertiesofMatrixAdditionandScalarMultiplication|Class12MathsQueryingDatafromaDatabaseusingfetchone()andfetchall()BasicPropertiesofElectricChargeGeeksforGeeksSchoolLibrariesinPythonHowtoConnectPythonwithSQLDatabase?EquationofaLinein3DDataCommunication-Definition,Components,Types,ChannelsDomainconstraintsinDBMSDegreeofRelationsinDBMSSQLHAVINGClausewithExamplesLogicGates-Definition,Types,UsesDifferencebetweenwrite()andwritelines()functioninPythonAlgebraSortingAlgorithmsinPythonWhatisanIPAddress?StatisticsGraphicalSolutionofLinearProgrammingProblemsCardinalityinDBMSSQLUSEDatabaseStatementShortestDistanceBetweenTwoLinesin3DSpace|Class12MathsCalculusBayes'TheoremClass12NCERTSolutions-MathematicsPartI-Chapter2InverseTrigonometricFunctions-Exercise2.1LinearProgrammingDotandCrossProductsonVectorsp-nJunctionDiode-Definition,Formation,Characteristics,ApplicationsInvertibleFunctionsTorqueonanElectricDipoleinUniformElectricFieldPropertiesofMatrixAdditionandScalarMultiplication|Class12MathsQueryingDatafromaDatabaseusingfetchone()andfetchall()BasicPropertiesofElectricChargeReadingRowsfromaCSVFileinPythonViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: BasicLastUpdated: 20Dec,2021ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle CSVstandsforCommaSeparatedValues.Thisfileformatisadelimitedtextfilethatusesacommaasadelimitertoseparatethetextpresentinit.Orinotherwords,CSVfilesareusedtostoredataintabularform.Asperthenamesuggested,thisfilecontainsthedatawhichisseparatedbyacommaandeverylineofafileisconsideredarecord.WecancreatetheCSVfileeitherfromnotepadorusingexcel. Example:Geeks,for,geeks one,of,the, top,learning,platformWecancreateaCSVfileusingthefollowingways:1.UsingNotepad:WecancreateaCSVfileusingNotepad.IntheNotepad,openanewfileinwhichseparatethevaluesbycommaandsavethefilewith.csvextension.2.UsingExcel:WecanalsocreateaCSVfileusingExcel.InExcel,openanewfileinwhichspecifyeachvalueinadifferentcellandsaveitwithfiletypeCSV.Toreaddatarow-wisefromaCSVfileinPython,wecanusereaderandDictReaderwhicharepresentintheCSVmoduleallowsustofetchdatarow-wise.UsingreaderUsingreaderwecaniteratebetweenrowsofaCSVfileasalistofvalues.ItiteratesoverallrowsinaCSVfileandfetchesdataineachrowasalist.reader()methodispresentinCSVlibrary.Sotousethisreadermethod,firstweneedtoimporttheCSVlibrary.readerobjectacceptsasingleparametercalledfileObject(avariablethatholdstheCSVfile). Syntax:csv.reader(fileobject)StepstoreadCSVfile:Step1:InordertoreadrowsinPython,First,weneedtoloadtheCSVfileinoneobject.Sotoloadthecsvfileintoanobjectuseopen()method.withopen('filename')asfileObjectWhileloadingthefilebyspecifyingpathalongwithfilename,ifyougotanyunicodeerrorthenappendrbeforepathoffilenamewithopen(r'path/filename')asfileObjectStep2:Createareaderobjectbypassingtheabove-createdfileobjecttothereaderfunction.reader_obj=csv.reader(file_obj)Step3:Useforlooponreaderobjecttogeteachrow.Example:ConsideraCSVfilenamed“samplecsv.csv”.Thisfilecontainsthefollowingdata:Id,Name,Rating 1,Akhil,4 2,Babu,3 3,Nikhil,5Python3#PythonprogramtoreadCSVfilelinebyline#importnecessarypackagesimportcsv  #Openfile withopen('samplecsv.csv')asfile_obj:          #Createreaderobjectbypassingthefile     #objecttoreadermethod    reader_obj=csv.reader(file_obj)          #Iterateovereachrowinthecsv     #fileusingreaderobject    forrowinreader_obj:        print(row)Output:['Id','Name','Rating'] ['1','Akhil','4'] ['2','Babu','3'] ['3','Nikhil','5']ReadingCSVfilewithoutheaderEverythingisfinewiththeaboveexamplebutifwedon’twantcolumnnamestofetchorwecansaywedon’twanttoreadtheheaderofthefile,thenweusethenext()methodonthefileobjectbeforecreatingthereaderobjectsothatitskipstheheadings.Python3#PythonprogramtoreadCSVfilewithoutheader  #Importnecessarypackagesimportcsv  #Openfilewithopen('samplecsv.csv')asfile_obj:          #Skipstheheading    #Usingnext()method    heading=next(file_obj)          #Createreaderobjectbypassingthefile     #objecttoreadermethod    reader_obj=csv.reader(file_obj)          #Iterateovereachrowinthecsvfile     #usingreaderobject    forrowinreader_obj:        print(row)Output:['1','Akhil','4'] ['2','Babu','3'] ['3','Nikhil','5']Explanation:TheabovecodeisalmostthesameasthecodeintheaboveexamplebutaslightchangeisweusethenextfunctionherethathelpsustoskipthecolumnnameswhileaccessingdatafromaCSVfilei.e.firstrow.Ifcolumnnamesarerequiredthenweaccessthemfromtheheadingobjecti.e.returntheresultofthenextmethod.UsingDictReaderWhenusingareader()methodwecaniterateoveraCSVfileasalistbutusingtheDictReaderclassobjectwecaniterateoveraCSVfilerowbyrowasadictionary.ThisDictReadermethodispresentinthecsvlibrary.Sotouseitfirstweneedtoimportthecsvlibrary.DictReader()acceptsasingleparametercalledfileObject(avariablethatholdsthecsvfile). Syntaxcsv.DictReader(fileobject)StepstoreadCSVfile:Step1:LoadtheCSVfileusingtheopenmethodinafileobject.withopen('filename')asfileObjectStep2:CreateareaderobjectwiththehelpofDictReadermethodusingfileobject.reader_obj=csv.DictReader(file_obj)Thisreaderobjectisalsoknownasaniteratorcanbeusedtofetchrow-wisedata.Step3:Useforlooponreaderobjecttogeteachrow.Example:Python3#Python3programtoreadCSVfileusingDictReader  #Importnecessarypackagesimportcsv  #Openfilewithopen('samplecsv.csv')asfile_obj:          #Createreaderobjectbypassingthefile    #objecttoDictReadermethod    reader_obj=csv.DictReader(file_obj)          #Iterateovereachrowinthecsvfile    #usingreaderobject    forrowinreader_obj:        print(row)Output:OrderedDict([('Id','1'),('Name','Akhil'),('Rating','4')]) OrderedDict([('Id','2'),('Name','Babu'),('Rating','3')]) OrderedDict([('Id','3'),('Name','Nikhil'),('Rating','5')])Explanation:Inthecode,firstweloadedtheCSVfilenamedsamplecsv.csvandthencreatedareader_objectthatcanbeiteratedtofetcheachrow.ThereturnedresultisintheformofKey-Valuepairindicatesitasadictionary.SousingDictReaderwereaddatarowbyrowasaDictionary.MyPersonalNotes arrow_drop_upSave LikePreviousIsAceafacecardoranumberedcard?Next Areallintegersrationalnumbers?RecommendedArticlesPage:28,Apr1731,May1726,Dec2103,Nov2026,Dec2126,Dec2126,Dec2126,Dec2127,Feb2027,Feb1809,Apr2018,Jan1926,Jan1803,May1913,Sep1612,Dec1619,May1716,Aug1801,Sep2111,Jul2118,Jul2104,Sep2118,May1709,Feb16ArticleContributedBy:akhilvasabhaktula03@akhilvasabhaktula03VotefordifficultyCurrentdifficulty: BasicEasy Normal Medium Hard ExpertArticleTags:PickedClass12SchoolLearningSchoolProgrammingReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?