Python Forum
How to import list from file? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to import list from file? (/thread-9385.html)



How to import list from file? - Epileptiker - Apr-05-2018

Hey, i've got a list inside a file like ["one", "two", "three"], which i'd like to import into my python script. I've tried it with
list1 = open("list1.txt", "r") but that didn't work. Could somebody help me with this please? I'm new to python and i just need to fix this one last problem.

This is the whole script.

import random, time, tweepy

list1 = open("list1.txt", "r")
list2 = open("list2.txt", "r")
list3 = open("list3.txt", "r")

def one():
    return random.choice(list1) + random.choice(list2)

def two():
    return random.choice(list2) + random.choice(list3)

#I'm working on a Twitter bot, that's just some twitter stuff down here 
consumer_key = 'XXX'
consumer_secret = 'XXX'
access_token = 'XXX'
access_token_secret = 'XXX'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

while True:
    postthis = random.choice([one,two])()
    if len(postthis) <= 140:
        api.update_status(status=postthis)
        time.sleep(10)
And the error message:

Traceback (most recent call last):
  File "C:/Users/User/Desktop/Example/example.py", line 22, in <module>
    postthis = random.choice([one,two])()
  File "C:/Users/User/Desktop/Example/example.py", line 11, in two
    return random.choice(list2) + random.choice(list3)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\random.py", line 256, in choice
    i = self._randbelow(len(seq))
TypeError: object of type '_io.TextIOWrapper' has no len()
>>>
I also don't understand the error has no len(). The content of my files are just very long lists, nothing else included. Maybe somebody has an alternative solution? Thanks so much :)


RE: How to import list from file? - Gribouillis - Apr-05-2018

You can use
import ast
with open('list1.txt') as infile:
    list1 = ast.literal_eval(infile.read())
The way you wrote things, list1 is an opened file object, not a list.

(Apr-05-2018, 04:47 PM)Epileptiker Wrote: I also don't understand the error has no len().
The call to random.choice() evaluates the length of its argument. Python informs you that an open file object has no method to compute its length.


RE: How to import list from file? - ajaykumar - Apr-05-2018

how do i can share my query to the forum


RE: How to import list from file? - Epileptiker - Apr-05-2018

Oh my god it works. Awesome, thank you so much!