0

I have a one line text file, file.txt which contents are:

["word 1","word 2","word 3","word 4"]

I want to open this file so that Python reads it as a list.

When I use:

line = (literal_eval(s) for s in open("file.txt"))

print(len(line))

I notice that line variable is a list with just one item, as that prints out 1

How do I open file.,txt to get a list with 4 items ("word 1", "word 2", "word 3", "word 4")?

Thanks.

Community
  • 1
  • 1
Tikolu
  • 193
  • 2
  • 12

1 Answers1

0

You could use (if you're sure the structure is as you mentioned it) :

line = '["word 1","word 2","word 3"]'
arr = line[1:-1].replace('"','').split(',')
print(arr) # => ['word 1', 'word 2', 'word 3'] as an array

A better, safe and easy way :

import json
line = '["word 1","word 2","word 3"]'
arr = json.loads(line)
print(arr) # => ['word 1', 'word 2', 'word 3'] as an array

To read the file's first line use :

import json
line = open('file.txt', 'r').read().splitlines()[0] # split lines and get the first one
arr = json.loads(line)
print(arr) # => ['word 1', 'word 2', 'word 3', 'word 4']
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55