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()
Answers:
Use the split method:
with open('abc.txt') as file:
A = file.read().strip("'").split("', '")
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))
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()
Use the split method:
with open('abc.txt') as file:
A = file.read().strip("'").split("', '")
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))