python使用csv模块读写csv文件

原文:https://www.getdatajoy.com/examples/python-data-analysis/read-and-write-a-csv-file-with-the-csv-module


Example that shows how to read and write a Comma Separated Value (cvs) filewith thecsv python module.

This example reads a file named smallsample.cvs whose column labels arefirst_name,last_name, company_name, address, city,county,postal, phone1, phone2,email, web. First the csv module isimported.

import csv

Now a new dialect called mydialect is created, the default dialect is excel

csv.register_dialect(
    'mydialect',
    delimiter = ',',
    quotechar = '"',
    doublequote = True,
    skipinitialspace = True,
    lineterminator = '\r\n',
    quoting = csv.QUOTE_MINIMAL)


Now we open and print the file and create an iterable object with thereader() routine, then we use afor loop to print the data.The with statement automatically closes the file when finished.

print('\n Output from an iterable object created from the csv file')
with open('smallsample.csv', 'rb') as mycsvfile:
    thedata = csv.reader(mycsvfile, dialect='mydialect')
    for row in thedata:
        print(row[0]+"\t \t"+row[1]+"\t \t"+row[4])


Output:

Output from an iterable object created from the csv file
first_name      last_name               city
Aleshia         Tomkiewicz              St. Stephens Ward
Evan            Zigomalas               Abbey Ward
France          Andrade                 East Southbourne and Tuckton W
Ulysses         Mcwalters               Hawerby cum Beesby
Tyisha          Veness                  Greets Green and Lyng Ward
Eric            Rampy                   Desborough
Marg            Grasmick                Bargate Ward
Laquita         Hisaw                   Chirton Ward
Lura            Manzella                Staple Hill Ward

Dictionary From CSV File

This example opens the file and makes a dictionary whose keys are theentries in the first row of the data file. TheDictReader() routineaccomplished this.The with statement automatically closes the file when finished

print("\n Now the output from a dictionary created from the csv file")
with open('smallsample.csv', 'rb') as mycsvfile:
    dictofdata = csv.DictReader(mycsvfile, dialect='mydialect')
    for row in dictofdata:
        print(row['first_name']+"\t "+row['phone1']+"\t "+row['city'])


Output:

Now the output from a dictionary created from the csv file
Aleshia  01835-703597    St. Stephens Ward
Evan     01937-864715    Abbey Ward
France   01347-368222    East Southbourne and Tuckton W
Ulysses  01912-771311    Hawerby cum Beesby
Tyisha   01547-429341    Greets Green and Lyng Ward
Eric     01969-886290    Desborough
Marg     01865-582516    Bargate Ward
Laquita  01746-394243    Chirton Ward
Lura     01907-538509    Staple Hill Ward

Write An Array To A CSV File

Now an example about writing, a file called mydata.csv with the contents ofthe arrayarrayofdata will be created. The file is created by thewriter() routine, then each row is written withwriterow().The with statement automatically closes the file when finished


arrayofdata=[[1,2,4,5,'something','spam',2.334],
             [3,1,6,3,'anything','spam',0]]
             
with open('mydata.csv', 'w') as mycsvfile:
    thedatawriter = csv.writer(mycsvfile, dialect='mydialect')
    for row in arrayofdata:
        thedatawriter.writerow(row)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Pythoncsv模块可以很方便地读取CSV文件。首先,你需要确保你已经关闭了正在使用CSV文件。然后,你可以按照以下步骤来读取CSV文件: 1. 首先,导入csv模块:`import csv` 2. 打开CSV文件并创建一个文件对象:`file = open('filename.csv', 'r')` 3. 通过csv模块的reader函数创建一个reader对象:`reader = csv.reader(file)` 4. 使用for循环遍历reader对象,逐行读取CSV文件的内容:`for row in reader:` 5. 在循环中,可以通过索引访问每一列的值,例如`row`代表第一列的值。 下面是一个示例代码,演示了如何使用csv模块读取CSV文件: ``` import csv # 打开CSV文件并创建一个文件对象 file = open('filename.csv', 'r') # 通过csv模块的reader函数创建一个reader对象 reader = csv.reader(file) # 使用for循环遍历reader对象,逐行读取CSV文件的内容 for row in reader: # 在循环中,可以通过索引访问每一列的值 print(row<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [使用python自带CSV模块读写csv文件](https://blog.csdn.net/qq_42215863/article/details/124358808)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值