How to save certain number of header in a file out of total header in file in python?

Hi I have 300 headers but need to save 100-100 headers in a file. Could you please help me how to do this?

Example:

headers = 'chai_patient_id,alcoholstatus_current_drinker,alcoholstatus_non_drinker...................condition_abnormal_results_of_liver_function_studies'

I need to save 1-100 headers in file1.csv, 101-200 headers in file2.csv and 201-300 headers in file3.csv

3 answers

  • answered 2021-04-21 11:19 Amit Nanaware

    you can try something like this:

    import csv
    data = "read your data hear"
    headers = "your,headers,are,hear,.......,"
    headers = headers.split(",")
    
    with open("somefile.csv",'w') as fp:
        some_headers = headers[:100]
        writer = csv.DictWriter(fp,fieldnames=some_headers)
        d = {"header1":"valueone"} # prepare your data
        writer.writeheader()
        writer.writerow(d)
        
    repeat above code for multiple files
    

  • answered 2021-04-21 11:22 AntiMatterDynamite

    maybe you're looking for something like this:

    def chunks(lst, n):
        for i in range(0, len(lst), n):
            yield lst[i:i + n]
    

    which would let you iterate over chunks of a given size so if you have your list of headers with headers.split(',') you can use it like this:

    for n, headers_chunk in enumerate(chunks(headers.split(','), 100)):
        with open("file{}.csv".format(n), "w") as output_csv:
            for header in headers_chunk:
                f.write(header + ",")
                
    

  • answered 2021-04-21 11:32 Horla.li

    first split the header into a list of seperated by the comma. separate the list files and write them to a files

       header = header.split(sep=',')
        file1 = header[0:100]
        file2 = header[100:200]
        file3 = header[200:]
        
        with open('file1.txt', 'w') as files:
            files.writelines('%s\n' % head for head in file1)
        
        with open('file2.txt', 'w') as files:
            files.writelines('%s\n' % head for head in file2)
        
        with open('file3.txt', 'w') as files:
            files.writelines('%s\n' % head for head in file3)
    

    This is not a DRY code but it does the job