读写CSV文件

学习内容:

使用csv模块和pandas模块读取csv文件并将文件内容写入输出文件。

#csv模块
import sys
import csv

input_file = sys.argv[1]
output_file = sys.argv[2]

with open(input_file,'r',newline='') as csv_in_file:
    with open(output_file,'w',newline='') as csv_out_file:
        filereader = csv.reader(csv_in_file,delimiter=',')
        filewriter = csv.writer(csv_out_file,delimiter=',')
        for row_list in filereader:
            print (row_list)
            filewriter.writerow(row_list)
#pandas模块
import sys
import pandas as pd
input_file = sys.argv[1]
output_file = sys.argv[2]
data_frame = pd.read_csv(input_file)
print(data_frame)
data_frame.to_csv(output_file,index=False)

使用特定条件筛选csv文件中特定的行,并将筛选的行写入输出文件。

#csv模块
import sys
import csv

input_file = sys.argv[1]
output_file = sys.argv[2]

with open(input_file,'r',newline='') as csv_in_file:
    with open(output_file,'w',newline='') as csv_out_file:
        filereader = csv.reader(csv_in_file)
        filewriter = csv.writer(csv_out_file)
        header = next(filereader)
        filewriter.writerow(header)
        for row_list in filereader:
            supplier = str(row_list[0]).strip()
            cost = str(row_list[3]).strip('$').replace(',','')
            if supplier == 'Supplier Z' or float(cost) > 600.0:
                filewriter.writerow(row_list)
#pandas模块
import sys
import pandas as pd

input_file = sys.argv[1]
output_file = sys.argv[2]

data_frame = pd.read_csv(input_file)
data_frame['Cost'] = data_frame['Cost'].str.strip('$').astype(float)
data_frame_value_meets_condition = data_frame.loc[(data_frame['Supplier Name']\
.str.contains('Z')) | (data_frame['Cost'] > 600.0),:]

data_frame_value_meets_condition.to_csv(output_file,index=Falsed)

你可能感兴趣的:(读写CSV文件)