Skip to main content
  1. About
  2. For Teams
Asked
Viewed 26k times
7

I am opening a csv called Remarks_Drug.csv which contains product names and mapped filenames in consecutive columns. I am doing some operations on the product column to remove all string content after + character. After stripping the string from + characters, I am storing the result in a variable called product_patterns.

Now I am opening a new csv and I want to write the output from the for loop into two columns, the first one containing the product_patterns and the second one containing the corresponding filenames.

What I am getting as output now is only the last row of the output csv that I am looking for. I think I am not looping properly so that each row of product_patterns and filename gets appended in the output csv file.

Can someone please help me with this.

Attaching code below:

import csv


with open('Remarks_Drug.csv', newline='', encoding ='utf-8') as myFile:
    reader = csv.reader(myFile)
    for row in reader:
        product = row[0].lower()
        #print('K---'+ product)
        filename = row[1]
        product_patterns = ', '.join([i.split("+")[0].strip() for i in product.split(",")])


        #print(product_patterns, filename)

    with open ('drug_output100.csv', 'a') as csvfile:
        fieldnames = ['product_patterns', 'filename']
        print(fieldnames)
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        print(writer)
        #writer.writeheader()
        writer.writerow({'product_patterns':product_patterns, 'filename':filename})

Sample input:

    Film-coated tablet + TERIFLUNOMIDE, 2011-07-18 - Received approval letter_EN.txt
    Film-coated tablet + VANDETANIB,             2013-12-14 RECD Eudralink_Caprelsa II-28 - RSI - 14.12.2017.txt
    Solution for injection + MenQuadTT, 395_EU001930-PIP01-16_2016-02-22.txt
    Solution for injection + INSULIN GLARGINE,  2017-11-4 Updated PR.txt
    Solution for injection + INSULIN GLARGINE + LIXISENATIDE,   2017 12 12 Email Approval Texts - SA1006-.txt
13
  • Can you please post example data?
    Bussller
    –  Bussller
    2019-02-27 07:47:15 +00:00
    Commented Feb 27, 2019 at 7:47
  • 1
    csv.DictWriter uses a dictionary for each row (with keys being the field names and values being the value for the corresponding cell), and you've only written one row.
    TigerhawkT3
    –  TigerhawkT3
    2019-02-27 07:47:26 +00:00
    Commented Feb 27, 2019 at 7:47
  • Yeah, I am unable to iterate over it
    checkmate
    –  checkmate
    2019-02-27 07:55:58 +00:00
    Commented Feb 27, 2019 at 7:55
  • Added example data in existing code.
    checkmate
    –  checkmate
    2019-02-27 07:56:29 +00:00
    Commented Feb 27, 2019 at 7:56
  • Because, you have a list and not dictionary
    Bussller
    –  Bussller
    2019-02-27 07:56:32 +00:00
    Commented Feb 27, 2019 at 7:56

2 Answers 2

3
import csv
import pandas as pd

with open('Remarks_Drug.csv', newline='', encoding ='utf-8') as myFile:
    reader = csv.reader(myFile)
    mydrug = []
    for row in reader:
        product = row[0].lower()
        #print('K---'+ product)
        filename = row[1]
        product_patterns = ', '.join([i.split("+")[0].strip() for i in product.split(",")])
        mydrug.append([product_patterns, filename])

#     print(mydrug)

    df = pd.DataFrame(mydrug, columns=['product_patterns', 'filename'])
    print(df)
    df.to_csv('drug_output100.csv', sep=',', index=False)

This utilizes pandas library. If you're to deal with large csv files using pandas will be handy and efficient in terms of performance and memory. This is just an alternative solution for the above.

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

Comments

2

I hope this is the right way for you, if is not, tell me and we check.

import csv

with open('Remarks_Drug.csv') as myFile:
    reader = csv.reader(myFile)
    products_list = list()
    filenames_list = list()

    for row in reader:
        products_list.append(row[0].lower().split("+")[0].strip())
        filenames_list.append(row[1])

    for index, product in enumerate(products_list):
        with open ('drug_output100.csv', 'a') as csvfile:
            fieldnames = ['product_patterns', 'filename']
            print(fieldnames)
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            print(writer)
            writer.writerow({'product_patterns':product, 'filename':filenames_list[index]})
  1. Open the Remarks_Drug.csv file and create two list where store the row value elaborated as you prefer.
  2. Iterate on the product list and enumerate it so you have an index to use on the filename list.
  3. Open the output file and append to it the result.

You can also use pandas to elaborate csv files, faster and in a smart way.

Here the pandas solution:

import pandas as pd

def select_real_product(string_to_elaborate):
    return string_to_elaborate.split('+')[0].strip()

df = pd.read_csv("Remarks_Drug.csv", delimiter=',', names=("product", "filename"))

df['product'] = df['product'].apply(select_real_product)

df.to_csv("drug_output100.csv", sep=',', na_rep='empty',index_label=False, index=False)

6 Comments

Works perfect. Thanks a lot.
Check also the pandas solution. I think is better and working with pandas is fun. You can do more with pandas and csv file.
Thanks. Sure, I will check and clarify with you if I have got any doubts
Ok well, I think that pandas is the best solution, for smallest files and also biggest files.
What's happend? Why you have removed my answer as correct?
|

Your Answer

Post as a guest

Required, but never shown

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.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.