How to Write to CSV Files in Python
文章推薦指數: 80 %
Steps for writing a CSV file · First, open the CSV file for writing ( w mode) by using the open() function. · Second, create a CSV writer object by calling the ... SkiptocontentHome»PythonBasics»PythonWriteCSVFileSummary:inthistutorial,you’lllearnhowtowritedataintoaCSVfileusingthebuilt-incsvmodule.StepsforwritingaCSVfileTowritedataintoaCSVfile,youfollowthesesteps:First,opentheCSVfileforwriting(wmode)byusingtheopen()function.Second,createaCSVwriterobjectbycallingthewriter()functionofthecsvmodule.Third,writedatatoCSVfilebycallingthewriterow()orwriterows()methodoftheCSVwriterobject.Finally,closethefileonceyoucompletewritingdatatoit.Thefollowingcodeillustratestheabovesteps:importcsv #openthefileinthewritemode f=open('path/to/csv_file','w') #createthecsvwriter writer=csv.writer(f) #writearowtothecsvfile writer.writerow(row) #closethefile f.close() Codelanguage:Python(python)It’llbeshorterifyouusethewithstatementsothatyoudon’tneedtocalltheclose()methodtoexplicitlyclosethefile:importcsv #openthefileinthewritemode withopen('path/to/csv_file','w')asf: #createthecsvwriter writer=csv.writer(f) #writearowtothecsvfile writer.writerow(row) Codelanguage:PHP(php)Ifyou’redealingwithnon-ASCIIcharacters,youneedtospecifythecharacterencodingintheopen()function.ThefollowingillustrateshowtowriteUTF-8characterstoaCSVfile:importcsv #openthefileinthewritemode withopen('path/to/csv_file','w',encoding='UTF8')asf: #createthecsvwriter writer=csv.writer(f) #writearowtothecsvfile writer.writerow(row) Codelanguage:PHP(php)WritingtoCSVfilesexampleThefollowingexampleshowshowtowritedatatotheCSVfile:importcsv header=['name','area','country_code2','country_code3'] data=['Afghanistan',652090,'AF','AFG'] withopen('countries.csv','w',encoding='UTF8')asf: writer=csv.writer(f) #writetheheader writer.writerow(header) #writethedata writer.writerow(data) Codelanguage:PHP(php)Ifyouopenthecountries.csv,you’llseeoneissuethatthefilecontentshaveanadditionalblanklinebetweentwosubsequentrows:Toremovetheblankline,youpassthekeywordargumentnewline=''totheopen()functionasfollows:importcsv header=['name','area','country_code2','country_code3'] data=['Afghanistan',652090,'AF','AFG'] withopen('countries.csv','w',encoding='UTF8',newline='')asf: writer=csv.writer(f) #writetheheader writer.writerow(header) #writethedata writer.writerow(data)Codelanguage:PHP(php)Output:WritingmultiplerowstoCSVfilesTowritemultiplerowstoaCSVfileatonce,youusethewriterows()methodoftheCSVwriterobject.Thefollowingusesthewriterows()methodtowritemultiplerowsintothecountries.csvfile:importcsv header=['name','area','country_code2','country_code3'] data=[ ['Albania',28748,'AL','ALB'], ['Algeria',2381741,'DZ','DZA'], ['AmericanSamoa',199,'AS','ASM'], ['Andorra',468,'AD','AND'], ['Angola',1246700,'AO','AGO'] ] withopen('countries.csv','w',encoding='UTF8',newline='')asf: writer=csv.writer(f) #writetheheader writer.writerow(header) #writemultiplerows writer.writerows(data) Codelanguage:PHP(php)WritingtoCSVfilesusingtheDictWriterclassIfeachrowoftheCSVfileisadictionary,youcanusetheDictWriterclassofthecsvmoduletowritethedictionarytotheCSVfile.TheexampleillustrateshowtousetheDictWriterclasstowritedatatoaCSVfile:importcsv #csvheader fieldnames=['name','area','country_code2','country_code3'] #csvdata rows=[ {'name':'Albania', 'area':28748, 'country_code2':'AL', 'country_code3':'ALB'}, {'name':'Algeria', 'area':2381741, 'country_code2':'DZ', 'country_code3':'DZA'}, {'name':'AmericanSamoa', 'area':199, 'country_code2':'AS', 'country_code3':'ASM'} ] withopen('countries.csv','w',encoding='UTF8',newline='')asf: writer=csv.DictWriter(f,fieldnames=fieldnames) writer.writeheader() writer.writerows(rows) Codelanguage:PHP(php)Howitworks.First,definevariablesthatholdthefieldnamesanddatarowsoftheCSVfile.Next,opentheCSVfileforwritingbycallingtheopen()function.Then,createanewinstanceoftheDictWriterclassbypassingthefileobject(f)andfieldnamesargumenttoit.Afterthat,writetheheaderfortheCSVfilebycallingthewriteheader()method.Finally,writedatarowstotheCSVfileusingthewriterows()method.SummaryUsetheCSVWriterortheDictWriterclasstowritedatatoaCSVfile.PreviouslyPythonReadCSVFileUpNextPythonDeleteFileSearchfor:GettingStartedPythonFundamentalsControlFlowFunctionsPythonListPythonDictionaryPythonSetExceptionHandlingPythonLoopwithElseClauseMoreonFunctionsModulesFileI/ODirectoryManagingThird-partyPackages
延伸文章資訊
- 1Writing to CSV in Python - codingem.com
The 4 Steps to Writing a CSV in Python · Open a CSV file in the write mode. This happens using th...
- 2Reading and Writing CSV Files in Python - Real Python
Reading from a CSV file is done using the reader object. The CSV file is opened as a text file wi...
- 3如何在Python 中把列表寫入CSV
可以使用Python 列表值來編寫csv 檔案。像csv.writer()、writerow()、pandas 和numpy 庫這樣的方法都是用於這個目的的。
- 4Python 讀取與寫入CSV 檔案教學與範例 - G. T. Wang
這裡介紹如何在Python 中使用 csv 模組,讀取與寫入逗點分隔檔。 ... import csv # 開啟輸出的CSV 檔案 with open('output.csv', 'w', ne...
- 5Python CSV: Read and Write CSV files - Programiz
To write to a CSV file in Python, we can use the csv.writer() function. The csv.writer() function...