2

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 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the response Andrej. However, my query was for .csv files and not .txt format. What I meant in my question was that I have tried the same operation for .txt files and it's straightforward but I do not get a solution for .csv files.

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.