Home > Software design >  CSV File Comma Insertion
CSV File Comma Insertion

Time:02-24

I'm a complete newb with Python so please excuse my ignorance. I'm trying to read items in a csv file and output the values with a comma in between (and no comma at the end).

My csv file (test.csv) is as follows:

Test
AAA
BBB
CCC

and the code I'm currently using is:

from csv import DictReader
with open('test.csv', 'r') as read_obj:
    csv_dict_reader = DictReader(read_obj)
    for row in csv_dict_reader:
       print('`' row['Test'] '`,')

This returns the following:

`AAA`,
`BBB`,
`CCC`,

Is there any way to have the comma remain after AAA and BBB, but not after CCC?

Thanks in advance.

CodePudding user response:

from csv import DictReader
with open('test.csv', 'r') as read_obj:
    csv_dict_reader = DictReader(read_obj)
    for row in csv_dict_reader:
       temp = '`' row['Test'] '`,'
       print(temp[:-1])

OR in case you like to read in as df then

import pandas as pd
df = pd.read_csv('test.csv')

Now, see df

CodePudding user response:

import csv
from csv import DictReader
with open("test.csv") as read_obj:
   csv_dict_reader = DictReader(read_obj)
   for row in csv_dict_reader:
      print('`' row['Test'] '`,'[:-1])

You can try this as well, this will print till second last character. So basically every last occurrence of comma will be removed.

CodePudding user response:

The easiest way to modify what you have to do what you want is to store the values and then you can use ",\n".join() on the list.

from csv import DictReader
data = []
with open('test.csv', 'r') as read_obj:
    csv_dict_reader = DictReader(read_obj)
    for row in csv_dict_reader:
       data.append(row['Test'])

print(",\n".join([f"`{item}`" for item in data]))

If you had a long list or a more complicated CSV, then you could take advantage of print("sometext", end="") to avoid the new line character. Then you can start each subsequent row with print(',') which will also provide you with the \n character.

from csv import DictReader

first = True
with open('test.csv', 'r') as read_obj:
    csv_dict_reader = DictReader(read_obj)
    for row in csv_dict_reader:
        if not first:
            print(',')
        print(f"`{row['Test']}`", end='')
        first = False

If your CSV is just a single column, you could use pathlib to grab the lines, slice off the first line with [1:] and then use the same join pattern on the remainder of the data.

from pathlib import Path
data = Path("test.csv").read_text().splitlines()[1:]
print(",\n".join([f"`{item}`" for item in data]))

Finally, as previously mentioned, pandas can be used to read the CSV and then you don't have to worry about the first line.

import pandas as pd
df = pd.read_csv('test.csv')
print(",\n".join([f"`{item}`" for item in df['Test'].values]))

All of these methods yield the following:

`AAA`,
`BBB`,
`CCC`
  • Related