知行编程网知行编程网  2022-10-28 03:30 知行编程网 隐藏边栏  12 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于python中不同的CSV功能和使用的相关知识,希望可以帮到处于编程学习途中的小伙伴

python中不同的CSV函数和用法

在之前的文章中介绍过为什么python学习中会使用
?这边文章将会详细介绍python中不同的CSV功能和使用。



一、CSV模块功能

在CSV模块下,可以找到以下功能

python中不同的CSV函数和用法


二、Python中CSV文件操作

加载 CSV 文件后,你可以执行各种操作。将在 Python 中显示对 CSV 文件的读取和写入操作

在Python中读取CSV文件:

import csv 
 
with open('Titanic.csv','r') as csv_file: #Opens the file in read mode
    csv_reader = csv.reader(csv_file) # Making use of reader method for reading the file
 
    for line in csv_reader: #Iterate through the loop to read line by line
        print(line)

用Python写入CSV文件:

import csv 
with open('Titanic.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file) 
    with open('new_Titanic.csv', 'w') as new_file: # Open a new file named 'new_titanic.csv' under write mode
        csv_writer = csv.writer(new_file, delimiter=';') #making use of write method
 
        for line in csv_reader: # for each file in csv_reader
            csv_writer.writerow(line) #writing out to a new file from each line of the original file

读取CSV文件作为字典

import csv 
 
with open('Titanic.csv','r') as csv_file: #Open the file in read mode
    csv_reader = csv.DictReader(csv_file) #use dictreader method to reade the file in dictionary
 
    for line in csv_reader: #Iterate through the loop to read line by line
        print(line)

作为字典写入CSV文件

import csv 
 
mydict = [{'Passenger':'1', 'Id':'0', 'Survived':'3'}, #key-value pairs as dictionary obj
          {'Passenger':'2', 'Id':'1', 'Survived':'1'},
          {'Passenger':'3', 'Id':'1', 'Survived':'3'}]
 
fields = ['Passenger', 'Id', 'Survived'] #field names
 filename = 'new_Titanic.csv' #name of csv file
 with open('new_Titanic.csv', 'w')as new_csv_file: #open a new file 'new_titanic,csv' under write mode
    writer = csv.DictWriter(new_csv_file, fieldnames=fields) 
    writer.writeheader() #writing the headers(field names)
 
    writer.writerows(mydict) #writing data rows

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享