Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding a comma to end of first row of csv files within a directory using python

Ive got some code that lets me open all csv files in a directory and run through them removing the top 2 lines of each file, Ideally during this process I would like it to also add a single comma at the end of the new first line (what would have been originally line 3)

Another approach that’s possible could be to remove the trailing comma’s on all other rows that appear in each of the csvs.

Any thoughts or approaches would be gratefully received.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import glob

path='P:\pytest'
for filename in glob.iglob(path+'/*.csv'):
  with open(filename, 'r') as f:
    lines = f.read().split("\n")
    f.close()
    if len(lines) >= 1:
      lines = lines[2:]
      o = open(filename, 'w')
      for line in lines:
        o.write(line+'\n')
      o.close()

>Solution :

adding a counter in there can solve this:

import glob

path=r'C:/Users/dsqallihoussaini/Desktop/dev_projects/stack_over_flow'
for filename in glob.iglob(path+'/*.csv'):
  with open(filename, 'r') as f:
    lines = f.read().split("\n")
    print(lines)
    f.close()
    if len(lines) >= 1:
      lines = lines[2:]
      o = open(filename, 'w')
      counter=0
      for line in lines:
        counter=counter+1
        if counter==1:
            o.write(line+',\n')
        else:
            o.write(line+'\n')
      o.close()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading