如果文件已经存在,则追加到CSV文件

时间:2018-12-12 14:21:38

标签: python python-3.x csv

我有一个如下的python脚本:

import argparse

if __name__ == "__main__":
   parser = argparse.ArgumentParser(description="This program parses CSV file for Agris Input from the files that are recieved from BOA",
                                epilog="*** Important not, leave the .csv off of the second argument so it does not end up in the file name.**")
   parser.add_argument('Input', help="Enter the name of the CSV file no extension.")
   parser.add_argument('Output', help="This is the output file that will be split into multiple files in the formation <outfile>_dataset_{number}.csv \nLeave the .csv extension off.")

  args = parser.parse_args()


import pandas as pd
import os
import sys

fileName = args.Input + ".csv"
outfile = args.Output

# Read data from the input file
data = pd.read_csv(fileName, sep='|', header=0)

if os.path.exists(outfile+".csv"):
   append_write = 'a' #appends if exists
   with open(output + group in data.groupyb('Number1')+'.csv', append_write) as f:
      group.to_csv(f, header=false, index=False, sep='|', float_format='%.2f')
else:
   append_write = 'w' #make a new file if it does not exist
   for Number1, group in data.groupby('Number1'):
       group.to_csv(f'{outfile}_{Number1}.csv', header=True, index=False, sep='|', float_format='%.2f')

我想要的是是否存在从该文件创建的文件,然后将数据追加到该文件,如果没有,则创建一个新文件。

所以例子是

python inOut.py book1 abc     #book1 is a csv | delimited file breaking on column called Number1

因此输出将创建abc_100.csv,然后在您运行inOut.py book2 abc时,它将查看该abc_100.csv文件是否存在以及是否附加了数据。

上面的代码将覆盖数据而不附加到数据上。

0 个答案:

没有答案