0

Hello everyone I am learning python I am new I have a column in a csv file with this example of value: enter image description here

I want to divide the column programme based on that semi column into two columns for example

program 1: H2020-EU.3.1. program 2: H2020-EU.3.1.7.

This is what I wrote initially

import csv
import os
with open('IMI.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)
    
    with open('new_IMI.csv', ''w') as new_file:
              csv_writer = csv.writer(new_file, delimiter='\t')
              
    #for line in csv_reader:
       # csv_writer.writerow(line)

please note that after i do the split of columns I need to write the file again as a csv and save it to my computer

Please guide me

AhlemMustapha
  • 405
  • 5
  • 12

2 Answers2

1

you can use pandas with the following code:

import pandas as pd
df = pd.read_csv('new_IMI.csv', sep='\t')
df

assuming that you're in a jupyter notebook this will evaluate your dataframe and show the data inside you can access a specific column with df['columnName'] and specific line number with df.iloc[lineNumber]

nicofrlo
  • 156
  • 5
  • I think reading csv with pandas should work, there is even a method `read_csv` maybe there is a different encoding than utf-8 which is why it fails to load. If you can find out which encoding your file uses, then you could do pd.read_csv('new_IMI.csv', sep='\t', encoding='yourEncoding') you can find out the encoding of your file with: ` import magic blob = open('unknown-file', 'rb').read() m = magic.open(magic.MAGIC_MIME_ENCODING) m.load() encoding = m.buffer(blob)` with csv library I don't know how to do it sorry :/ – nicofrlo Dec 07 '21 at 11:33
0

Try this:

import pandas as pd

df = pd.read_csv('IMI.csv')
df['program 1'], df['program 2'] = df['programme'].str.split(';', 1).str
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50