Extracting individual elements from CSV file using python

Viewed 40

I have the task of converting the data available in csv files into JSON format. I did the same earlier for '.txt' files using the '.readlines()'. However, I cannot find any suitable methods for CSV. Right now I am converting the .csv files into .txt and then running the operations.

I have tried:

with open(file, 'r') as in_file: #file has .csv extension
    Lines = in_file.readlines()
    out_filename_a = vid_name+ "_" + ".json"
    for line in Lines:
        raw_list = line.strip().split(";")

Above code generates the desired outputs but somehow the iteration does not work properly. I have also tried:

import csv
with open('X:\data.csv', 'rt') as f:
    data = csv.reader(f)
    for row in data:
        print(row)

The generated output look like:['Programming language; Designed by; Appeared; Extension'] which is not really useful for me as it is a single element in the list and I need the individual elements extracted from the output.

1 Answers

If I understand you correctly, your file contains this string:

['Programming language; Designed by; Appeared; Extension']

to parse it, you can use next example:

from ast import literal_eval


with open("your_file.txt", "r") as f_in:
    for line in map(str.strip, f_in):
        if line == "":
            continue
        line = literal_eval(line)

        for item in map(str.strip, line[0].split(";")):
            print(item)

Prints:

Programming language
Designed by
Appeared
Extension
Related