CSV (comma-separator values) comma-separated value, because it is a plain text file, any editor can be opened. CSV file operation in CSV and pandas two ways
Raw CSV file contents
Supplier name,invoice number,part number,cost,purchase datesupplier X,001-1001,2341,$500.00, 1/20/14Supplier X,001-1001,2341,$500.00, 1/20/14Supplier X,001-1001,5467,$750.00, 1/20/14Supplier X,001-1001,5467,$750.00, 1/20/14Supplier Y,50-9501,7009,$250.00, 1/30/14Supplier Y,50-9501,7009,$250.00, 1/30/14Supplier Y,50-9505,6650,$125.00, 2002/3/14Supplier Y,50-9505,6650,$125.00, 2002/3/14Supplier Z,920-4803,3321,$615.00, 2002/3/14Supplier Z,920-4804,3321,$615.00, 2002/10/14Supplier Z,920-4805,3321,"$6,015.00", 2/17/14Supplier Z,920-4806,3321,"$1,006,015.00", 2/24/14
1. csv Package operation CSV file
#Coding=utf-8ImportSYSImportCSVImportReread_file= Sys.argv[1]write_file= Sys.argv[2]with Open (Read_file,"R") as Readfile:with open (Write_file,"W") as Writefile:reader= Csv.reader (ReadFile, delimiter=",") Writer= Csv.writer (WriteFile, delimiter=",") Header=Next (reader) Writer.writerow (header) forRowlistinchReader:#line matching is done by regular expression ifRe.match (R"^001-*.", str (rowlist[1])): Print(rowlist) writer.writerow (rowlist)
>>> D:\pystu>python parsecsvfile.py supplier_data.csv ceshi.csv
>>> Supplier name,invoice Number,part number,cost,purchase Date
>>> Supplier x,001-1001,2341,$500.00, 1/20/14
>>> Supplier x,001-1001,2341,$500.00, 1/20/14
>>> Supplier x,001-1001,5467,$750.00, 1/20/14
>>> Supplier x,001-1001,5467,$750.00, 1/20/14
2. Pandas package operation CSV file
#Coding=utf-8" "using the pandas package to parse a CSV file" "ImportPandas fromPandasImportSeries,dataframeImportSysfile_path= Sys.argv[1]write_path= Sys.argv[2]data_frame=pandas.read_csv (File_path)#print (data_frame)#Note the use of STRdata_frame[" Cost"] = data_frame[" Cost"].str.replace (",",""). Str.strip ("$"). Astype (float)#print (data_frame)Newa= data_frame.loc[data_frame[" Cost"] > 600, :]#print(Newa) newa.to_csv (Write_path, index= False)
>>> D:\pystu>python parse_csv_file_by_pandas.py supplier_data.csv ceshi.csv
>>> Supplier name,invoice Number,part number,cost,purchase Date
>>> Supplier X,001-1001,5467,750.0,1/20/14
>>> Supplier X,001-1001,5467,750.0,1/20/14
>>> Supplier Z,920-4803,3321,615.0,2002/3/14
>>> Supplier Z,920-4804,3321,615.0,2002/10/14
>>> Supplier Z,920-4805,3321,6015.0,2/17/14
>>> Supplier Z,920-4806,3321,1006015.0,2/24/14
Python--csv file Processing