Call a text file and put in an array in python

Question:

In a text file abc.txt, I have written like

'abc', 'edf', 'ghij'

From my python code, I want to creat an array A such that

A=['abc', 'edf', 'ghij']

How can I do this?

This is not solving the problem:

with open('abc.txt', 'r') as file:
    # Read the contents of the file into a variable
    AA = file.read()
Asked By: str

||

Answers:

Use the split method:

with open('abc.txt') as file:
    A = file.read().strip("'").split("', '")
Answered By: Jonathan Dauwe

Your input is really a CSV file with a single quote as the quote character and with spaces after commas skipped, so a more robust approach would be to use csv.reader to parse the input:

import csv

with open('abc.txt') as file:
    A = next(csv.reader(file, quotechar="'", skipinitialspace=True))

Demo: https://replit.com/@blhsing/DarkorangeLovableCarrier

Answered By: blhsing
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.