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

2
  • stackoverflow.com/questions/14745022/… might help - so would some examples of your before and after desired data. Commented Dec 7, 2021 at 10:52
  • Thank you but how to use pandas library in the code I wrote above ? Commented Dec 7, 2021 at 10:56

2 Answers 2

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]

Sign up to request clarification or add additional context in comments.

1 Comment

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 :/
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

2 Comments

Thank you this helped me a bit, how can I display all the rows in the result? cause now I get only colA and colB -> it is like all my data was stored in colA and colb
@AhlemMustapha What you're asking is very unclear. Please elaborate :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.