How to read one single line of csv data in Python?
文章推薦指數: 80 %
To read only the first row of the csv file use next() on the reader object. with open('some.csv', newline='') as f: reader = csv.reader(f) row1 ... Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. LearnmoreaboutCollectives Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. LearnmoreaboutTeams HowtoreadonesinglelineofcsvdatainPython? AskQuestion Asked 9years,3monthsago Modified 2years,6monthsago Viewed 306ktimes 115 Thereisalotofexamplesofreadingcsvdatausingpython,likethisone: importcsv withopen('some.csv',newline='')asf: reader=csv.reader(f) forrowinreader: print(row) Ionlywanttoreadonelineofdataandenteritintovariousvariables.HowdoIdothat?I'velookedeverywhereforaworkingexample. Mycodeonlyretrievesthevaluefori,andnoneoftheothervalues reader=csv.reader(csvfile,delimiter=',',quotechar='"') forrowinreader: i=int(row[0]) a1=int(row[1]) b1=int(row[2]) c1=int(row[2]) x1=int(row[2]) y1=int(row[2]) z1=int(row[2]) pythonfilecsviteratornext Share Improvethisquestion Follow editedAug27,2016at0:21 smci 30.6k1818goldbadges110110silverbadges145145bronzebadges askedJun23,2013at15:25 andrebrutonandrebruton 2,08844goldbadges2727silverbadges3535bronzebadges 1 whatisthestructureofyourcsv?Whatisrowwhenyouareiteratingthroughreader? – dm03514 Jun23,2013at15:27 Addacomment | 7Answers 7 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 158 Toreadonlythefirstrowofthecsvfileusenext()onthereaderobject. withopen('some.csv',newline='')asf: reader=csv.reader(f) row1=next(reader)#getsthefirstline #nowdosomethinghere #iffirstrowistheheader,thenyoucandoonemorenext()togetthenextrow: #row2=next(f) or: withopen('some.csv',newline='')asf: reader=csv.reader(f) forrowinreader: #dosomethingherewith`row` break Share Improvethisanswer Follow editedAug12,2016at8:12 answeredJun23,2013at15:29 AshwiniChaudharyAshwiniChaudhary 237k5656goldbadges446446silverbadges496496bronzebadges 3 2 Whathappensifyouwanttojustreadthefirstlineratherthaniterating?Thisapproachmovestheiteratortothenextlineandyou'lllosethevalueifyouwanttoiterateoverthewholelistagainlater. – MahsanNourani Jun8,2021at15:29 2 @MahsanNouraniThefilepointercanbemovedtoanywhereinthefile,file.seek(0)willmoveitbacktothestartforexampleandthenyoucanre-readfromstart.You'llhavetokeepthefileopenobviouslytoperformseekoperation.Ingeneral,thepointofusingiteratorsisthatyou'llgetoneitematime,hencesavingmemory,ifyouneedmultipleiterationonthesamedata,listisabetterdatastructure. – AshwiniChaudhary Jun9,2021at5:23 Iwasjusttryingtoprintthefirstlineofthefilebeforedoinganythingwiththedatahencemyquestion!Thissolutionisgreat,Ididn'tknowthat.Thanks:) – MahsanNourani Jun10,2021at1:11 Addacomment | 44 youcouldgetjustthefirstrowlike: withopen('some.csv',newline='')asf: csv_reader=csv.reader(f) csv_headings=next(csv_reader) first_line=next(csv_reader) Share Improvethisanswer Follow editedMay15,2019at11:51 answeredJun23,2013at15:29 dm03514dm03514 53.3k1818goldbadges104104silverbadges142142bronzebadges 1 2 Probably,itisgoodtoadd"withopen('csv_file','r')"asf:csv_reader=csv.reader(f)..." – Sanchit May15,2019at10:45 Addacomment | 28 YoucanusePandaslibrarytoreadthefirstfewlinesfromthehugedataset. importpandasaspd data=pd.read_csv("names.csv",nrows=1) Youcanmentionthenumberoflinestobereadinthenrowsparameter. Share Improvethisanswer Follow editedJun19,2015at18:48 josliber♦ 43.4k1212goldbadges9696silverbadges132132bronzebadges answeredJun19,2015at18:46 AravindKrishnakumarAravindKrishnakumar 2,61911goldbadge2626silverbadges2323bronzebadges Addacomment | 15 FromthePythondocumentation: Andwhilethemoduledoesn’tdirectlysupportparsingstrings,itcaneasilybedone: importcsv forrowincsv.reader(['one,two,three']): printrow Justdropyourstringdataintoasingletonlist. Share Improvethisanswer Follow editedApr7,2016at15:08 Luke 1,32911goldbadge1212silverbadges3737bronzebadges answeredJan23,2015at4:08 RobertElwellRobertElwell 6,53011goldbadge2828silverbadges3232bronzebadges Addacomment | 14 Justforreference,aforloopcanbeusedaftergettingthefirstrowtogettherestofthefile: withopen('file.csv',newline='')asf: reader=csv.reader(f) row1=next(reader)#getsthefirstline forrowinreader: print(row)#printsrows2andonward Share Improvethisanswer Follow answeredJan31,2020at22:20 EmersonPetersEmersonPeters 31322silverbadges99bronzebadges Addacomment | 8 Thesimplewaytogetanyrowincsvfile importcsv csvfile=open('some.csv','rb') csvFileArray=[] forrowincsv.reader(csvfile,delimiter='.'): csvFileArray.append(row) print(csvFileArray[0]) Share Improvethisanswer Follow answeredSep22,2016at3:07 Oscar.ChouOscar.Chou 8111silverbadge33bronzebadges 3 3 Tomakethisworkinpython3,justremovethe'b'in'rb' – RickyAvina Jan13,2018at22:57 1 Thisjustworks,actuallywithoutthedelimiter='.'. – suvtfopw Jan24,2019at7:05 1 Toanswerthepostersquestion,justaddabreakafterthecsvFileArray.append(row)anditwillonlyreadthefirstline. – StratusBaseLLC Sep17,2019at2:48 Addacomment | 5 Toprintarangeofline,inthiscasefromline4to7 importcsv withopen('california_housing_test.csv')ascsv_file: data=csv.reader(csv_file) forrowinlist(data)[4:7]: print(row) Share Improvethisanswer Follow answeredApr8,2020at14:01 BiplobDasBiplobDas 2,4342121silverbadges1313bronzebadges 1 Ionlygotthistoworkbyusingwithopen('C:\\Users\\username\\Desktop\\csv_file.csv',encoding='utf-8')ascsv_file:asthefirstline – jeppoo1 Apr7,2021at8:56 Addacomment | YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedpythonfilecsviteratornextoraskyourownquestion. TheOverflowBlog HowtoearnamillionreputationonStackOverflow:beofservicetoothers Therightwaytojobhop(Ep.495) FeaturedonMeta BookmarkshaveevolvedintoSaves Inboximprovements:markingnotificationsasread/unread,andafiltered... Revieweroverboard!Orarequesttoimprovetheonboardingguidancefornew... CollectivesUpdate:RecognizedMembers,Articles,andGitLab Shouldweburninatethe[script]tag? Visitchat Linked 6 Printrowsincsvfile? 1 Howtoprintfirstrowofafileasalist? 0 DisplaylinesofdatausingListorDictionary? 27 Reading.csvinPythonwithoutloopingthroughthewholefile? 2 Python:ExtractingfirstelementfromeachlineofaCSVfile -1 WhyDoesThisCodeProduceaListofLists? 1 Howtoremovedoublequotefromacsvfilebeforereadingit? -1 Howtomaketheprogramkeepsearchingforanotherusernameinthefile? 0 Parsingtextfileandstoringitinalist Related 6474 HowdoImergetwodictionariesinasingleexpression? 2277 HowtoconcatenatetextfrommultiplerowsintoasingletextstringinSQLServer 3246 HowdoIconcatenatetwolistsinPython? 2573 HowtoupgradeallPythonpackageswithpip? 2025 Howtoreadafileline-by-lineintoalist? 2898 HowdoIaccessenvironmentvariablesinPython? 3585 Catchmultipleexceptionsinoneline(exceptblock) 3063 HowdoIdeleteafileorfolderinPython? 2646 HowcanIremoveakeyfromaPythondictionary? HotNetworkQuestions WhytheneedforaScienceOfficeronacargovessel? Whataretheargumentsforrevengeandretribution? HowdoIsignafileusingSSHandverifyitusingacertificateauthority? Howtoremovetikznode? Whydoesthesameelectrontransitionreleasephotonsofdifferentfrequenciesforsomeelements? Doesindecentexposurerequireintentionality? Howdoyoucalculatethetimeuntilthesteady-stateofadrug? Levinson'salgorithmandQRdecompositionforcomplexleast-squaresFIRdesign Canyoufindit? tutorialto"motionblur"peopleonbackground MakeaCourtTranscriber WhathadEstherdonein"TheBellJar"bySylviaPlath? InD&D3.5,canafamiliarbetemporarilydismissed? Howtoplug2.5mm²strandedwiresintoapushwirewago? PacifistethosblockingmyprogressinStellaris IsdocumentingabigprojectwithUMLDiagramsneeded,goodtohaveorevennotpossible? Wouldextractinghydrogenfromthesunlessenitslifespan? Howtocreateamatrixofpairedvaluesfromtwomatrices? Whattranslation/versionoftheBiblewouldChaucerhaveread? Areyougettingtiredofregularcrosswords? Isitcorrecttochangetheverbto"being"in"Despitenoonewashurtinthisincident…"? Whyare"eat"and"drink"differentwordsinlanguages? ShouldIresendanapplication? Iwanttodothedoubleslitexperimentwithelectrons,but morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-py Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings
延伸文章資訊
- 1csv — CSV File Reading and Writing — Python 3.10.7 ...
The csv module implements classes to read and write tabular data in CSV format. ... in the dictio...
- 23 (Or More) Ways to Open a CSV in Python
The idea behind just opening a file and calling readlines() or readline() is that it's simple. Wi...
- 3Reading Rows from a CSV File in Python - GeeksforGeeks
Using reader we can iterate between rows of a CSV file as a list of values. It iterates over all ...
- 43 (Or More) Ways to Open a CSV in Python
- 5Python - Read csv file with Pandas without header? - Tutorialspoint