How do I read and write CSV files with Python?

后端 未结 4 1600
抹茶落季
抹茶落季 2020-11-21 23:14

I have a file example.csv with the contents

1,\"A towel,\",1.0
42,\" it says, \",2.0
1337,is about the most ,-1
0,massively useful thing ,123
-2         


        
4条回答
  •  不知归路
    2020-11-21 23:17

    To read a csv file using Pandas

    use pd.read_csv("D:\\sample.csv")
    
    using only python :
    
    fopen=open("D:\\sample.csv","r") 
    
    print(fopen.read())
    

    To create and write into a csv file

    The below example demonstrate creating and writing a csv file. to make a dynamic file writer we need to import a package import csv, then need to create an instance of the file with file reference Ex:

    with open("D:\sample.csv","w",newline="") as file_writer
    

    Here if the file does not exist with the mentioned file directory then python will create a same file in the specified directory, and w represents write, if you want to read a file then replace w with r or to append to existing file then a.

    newline="" specifies that it removes an extra empty row for every time you create row so to eliminate empty row we use newline="", create some field names(column names) using list like:

    fields=["Names","Age","Class"]
    

    Then apply to writer instance like:

    writer=csv.DictWriter(file_writer,fieldnames=fields)
    

    Here using Dictionary writer and assigning column names, to write column names to csv we use writer.writeheader() and to write values we use writer.writerow({"Names":"John","Age":20,"Class":"12A"}) ,while writing file values must be passed using dictionary method , here the key is column name and value is your respective key value.

    Import csv:

    with open("D:\sample.csv","w",newline="") as file_writer:
    
    fields=["Names","Age","Class"]
    
    writer=csv.DictWriter(file_writer,fieldnames=fields)
    
    writer.writeheader()
    
    writer.writerow({"Names":"John","Age":21,"Class":"12A"})
    

提交回复
热议问题