SoFunction
Updated on 2024-12-12

python read, write and append csv files with pandas

csv file

CSV files are one of the most commonly used forms of file storage. Comma-Separated Values (CSV) files store tabular data in plain text (note: the separator character can also be another character). Plain text indicates that the file is a sequence of characters and does not contain data that must be interpreted like a binary number.

CSV file consists of any number of records, records are separated by some kind of line break; each record consists of a number of fields, fields are separated by characters (such as commas) or strings.

I. Creating a csv file

示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。

Open it with Notepad as shown here

在这里插入图片描述

Second, read and write csv files

1. Basic python

import csv
with open('supplier_data.csv','r')as f:
    reader = (f)
    for row in reader:
        print(row)

在这里插入图片描述

import pandas as pd
df = pd.read_csv('supplier_data.csv')
print(df)

在这里插入图片描述

III. Appending csv files

1. Basic python

import csv
with open('supplier_data.csv','a') as f:
    writer = (f)
    (['7','hu','18','100','90','85'])
    (['8','zahng','19','87','97','77'])

在这里插入图片描述

At this point we find that the data added will be an empty line, to solve this problem we have to use newline=''

import csv
with open('supplier_data.csv','a',newline='') as f:
    writer = (f)
    (['7','hu','18','100','90','85'])
    (['8','zahng','19','87','97','77'])

在这里插入图片描述

在这里插入图片描述

At this point, the problem with the above code is solved

import pandas
a={'sid':[7],'sname':['hu'],'sage':[18],'math':[100],'english':[90],'cs':[85]}
df = (a)
#mode = 'a' for append data, index for index number of each line, header for title
df.to_csv('supplier_data.csv',mode='a',index=False,header=False)

summarize

to this article on python with pandas read and write and append csv files to this article, more related python pandas operation csv file content, please search my previous posts or continue to browse the following articles hope that you will support me in the future more!