Apr-24-2022, 06:41 AM
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:55Final 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:55The 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,NEMMy 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.
