How do I import a list ? (python)

How do I import a list ? (python)

Heres the answer in a generalized form:

f = open(path/to/file, r) # opens the file as read-only
content = # there are easier ways to do this, but....
### do whatever youre doing here....
f.close() # MAKE SURE YOU CLOSE FILES when youre done with them
# if you dont, youre asking for memory leaks.

You can also use a context manager, but its slightly harder to read:

with open(path/to/file,r) as f:
    content = # again, this is not the BEST way....
    ### do stuff with your file
# it closes automatically, no need to call f.close()

Outside of file operations, heres string -> list stuff:

-> [a,b,c,d,e,f,g]
# str.split creates a list from a string, splitting elements on
# whatever character you pass it.

And heres random.choice:

import random

-> c # chosen by fair dice roll, guaranteed to be random! ;)
# random.choice returns a random element from the list you pass it

Im going to give you an example that includes a few best practices:

my_list = [] 

Open the file with the context manager, with (which will automatically close the file if you have an error, as opposed to the other way youve been shown here), and with the Universal readlines, rU, flag enabled (r is the default).

with open(/path/file, rU) as file:
    for line in file:
        my_list.extend(line.split()) # this can represent processing the file line by line

The str.split() method will split on whitespace, leaving you with your punctuation. Use the Natural Language Toolkit if you really need words, which would help you preserve meaning better.

You could read the entire file all at once with

my_list =

And that may work for smaller files, but keep in mind difficulties with bigger files if you do this.

Use the random module to select your word (keep your imports to the top of your script, in most cases, though):

import random

my_random_word = random.choice(my_list)

How do I import a list ? (python)

Leave a Reply

Your email address will not be published. Required fields are marked *