Python Forum
Insert a multiple constant value after header in csv file using python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Insert a multiple constant value after header in csv file using python
#1
Is it possible to insert 9 new lines of Constant Value("AA") in a CSV starting from the 2nd row? I need to insert the "AA" at the top 9 rows(after the header).

Original CSV look like this:
LEID,MI_RL,TOTDEPTH, INSERTED
07JW01,51,120,2/10/2014 10:37
DD18006,40,10,20/10/2018 16:55
Final CSV should Look like this:
LEID,MI_RL,TOTDEPTH, INSERTED
AA,AA,AA,AA
AA,AA,AA,AA
AA,AA,AA,AA
AA,AA,AA,AA
AA,AA,AA,AA
AA,AA,AA,AA
AA,AA,AA,AA
AA,AA,AA,AA
AA,AA,AA,AA
07JW01,51,120,2/10/2014 10:37
DD18006,40,10,20/10/2018 16:55
The other issue is that every CSV has a different number of columns? see another csv file has 5 columns.
OLEID,FROM,TO,ZON,PROS
07WJ05,0,125,ARCN,ABC
DDH006,891.68,7854,BASE,DEF
DD1,25687,15987,GOOD,NEM
My code:
import os
   
def prepend_multiple_lines(file_name, list_of_lines):
    # define name of temporary dummy file
    dummy_file = file_name + '.csv'
    # open given original file in read mode and dummy file in write mode
    with open(file_name, 'r') as read_obj, open(dummy_file, 'w') as write_obj:
        # Iterate over the given list of strings and write them to dummy file as lines
        for line in list_of_lines:
            write_obj.write(line + '\n')
        # Read lines from original file one by one and append them to the dummy file
        for line in read_obj:
            write_obj.write(line)
    # remove original file
    os.remove(file_name)
    # Rename dummy file as the original file
    os.rename(dummy_file, file_name)
    
def main():
    print('*** Insert multiple lines from the second position of a file ***')
    list_of_lines = ['AA','AA','AA','AA','AA','AA','AA','AA','AA'] #add 9 AA constant value
    prepend_multiple_lines("DB_1.csv", list_of_lines)
    
if __name__ == '__main__':
   main()
The code is not working??? Can anyone help what is wrong with that code.
Reply
#2
Makes a change from doing sudokus!

Maybe like this, very simple:

def myApp():
    import csv
    import glob
    # maybe use linecache?
    #import linecache

    path2csv = '/home/pedro/myPython/csv/'
    files = glob.glob(path2csv + '*.csv')
    for f in files:
        print('The csv files are', f)
        
    myfile = input('copy and paste the file you want to modify ... ')

    with open(myfile) as mf:
        mylist = mf.readlines()

    mystring = input('What do you want to put in the columns? Enter a string like AA ... ')
    # could get the number of columns automatically by splitting mylist[0] and get the len(mylist[0].split(','))
    num_cols = input('How many columns of the string do you want? ')
    num_rows = input('How many rows of columns with the string do you want? ')

    # make 1 row
    a_row = ''
    for i in range(int(num_cols)):
        if not i == int(num_cols) -1:
            a_row = a_row + mystring + ','
        else:
            a_row = a_row + mystring + '\n'

    insert_string = int(num_rows) * a_row
    headers = mylist[0]
    new_start = headers + insert_string
    # get a slice of mylist without the headers
    new_list = mylist[1:]
    new_list_string = ''.join(new_list)
    new_csv_string = new_start + new_list_string
    with open(path2csv + 'modified_csv.csv', 'w') as nf:
        nf.write(new_csv_string)

    # check the result
    with open(path2csv + 'modified_csv.csv') as infile:
        result = csv.reader(infile)
        for line in result:
            print(line)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python convert multiple files to multiple lists MCL169 6 1,535 Nov-25-2023, 05:31 AM
Last Post: Iqratech
  Insert 10gb csv files into sql table via python mg24 2 1,905 Apr-28-2023, 04:14 PM
Last Post: snippsat
  Python Serial: How to read the complete line to insert to MySQL? sylar 1 819 Mar-21-2023, 10:06 PM
Last Post: deanhystad
  python pandas sql table with header mg24 3 1,947 Dec-08-2022, 08:31 PM
Last Post: Larz60+
  python insert blank line in logger mg24 1 2,831 Nov-02-2022, 08:36 AM
Last Post: snippsat
  python run multiple file paralaly mg24 2 853 Oct-11-2022, 06:08 PM
Last Post: deanhystad
  Insert header at first row, for existing csv mg24 2 2,064 Oct-05-2022, 07:12 AM
Last Post: mg24
  Add\insert header row existing csv files mg24 0 714 Oct-05-2022, 06:11 AM
Last Post: mg24
  Python create a spreadsheet with column and row header ouruslife 4 1,617 Jul-09-2022, 11:01 AM
Last Post: Pedroski55
  How to keep columns header on excel without change after export data to excel file? ahmedbarbary 0 1,161 May-03-2022, 05:46 PM
Last Post: ahmedbarbary

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020