0

So, let’s say that names.txt contains the following:

["John", "Mike", "Tom", "Sam", "Anthony"]

How can I have a list by the name of names be names.txt? If I explained horribly (which I probably did), here’s what I want:

names = names.txt

How can I have names list all of the objects in names.txt?

Henry Woody
  • 14,024
  • 7
  • 39
  • 56

5 Answers5

0

This will read the contents of your "names.txt" file into the variable "names":

with open('names.txt') as f:
   names = f.read()
Christian Sloper
  • 7,440
  • 3
  • 15
  • 28
0

Does the file parse as JSON? If so, reading it into a list is cake:

names = []
with open('names.txt') as filen:
    names = json.loads(filen.read())
hd1
  • 33,938
  • 5
  • 80
  • 91
  • Given that when the file is closed by the garbage collector would be non-deterministic, the ```with..as...``` form would be preferred. See this [answer](https://stackoverflow.com/questions/22348859/will-passing-open-as-json-load-parameter-leave-the-file-handle-open). – Steve Boyd Mar 10 '19 at 19:48
0

f = open("names.txt", "r")

names = f.read()

Abhay Prakash
  • 81
  • 1
  • 3
0

If names.txt has exactly this type of data (with '[', ']') as mentioned:

["John", "Mike", "Tom", "Sam", "Anthony"]

Then the following code can be used:

names = [name[1:-1] for name in open('names.txt').read()[1:-1].split(', ')]
>>> print(names)
['John', 'Mike', 'Tom', 'Sam', 'Anthony']

Or if names.txt consists of many lines, and each line has one name, you can do the following:

names = [line for line in open('names.txt').readlines()]
>>> ['John', 'Mike', 'Tom', 'Sam', 'Anthony']

Or if it has names separated by comma (or any other symbol), then:

names = open('names.txt').read().split(',')  # you can change ',' for any other separator you need
print(names)
>>> ['John', 'Mike', 'Tom', 'Sam', 'Anthony']

Note that some text editors (like Atom) add an empty line when saving the file, so it can produce '\n' character presence in your list.

Also note that in the first case (one line - one name) each line will end with '\n' character.

-1

You can firsly get your data from data as a string :

names = []
with open("names.txt") as file:
    names = file.read()    

Then convert the string as a list:

    names = eval(names)
yoadev
  • 149
  • 6