read in a list in a file to list

breamoreboy at gmail.com breamoreboy at gmail.com
Sat Apr 8 16:21:08 EDT 2017


On Saturday, April 8, 2017 at 7:32:52 PM UTC+1, john polo wrote:
> Hi,
> 
> I am using Python 3.6 on Windows 7.
> 
> I have a file called apefile.txt. apefile.txt's contents are:
> 
> apes =  "Home sapiens", "Pan troglodytes", "Gorilla gorilla"
> 
> I have a script:
> 
> apefile =  open("apefile.txt")
> apelist =  apefile.read()
> for ape in apelist:
>     print("one of the apes is " + ape)
> apefile.close()
> 
> The output from the script does not print the ape names, instead it 
> prints each letter in the file. For example:
> 
> one of the apes is a
> one of the apes is p
> one of the apes is e
> 
> What should I do instead to get something like
> 
> one of the apes is Home sapiens
> one of the apes is Pan troglodytes
> one of the apes is Gorilla gorilla
>  
> John

I'll start you off.

with open("apefile.txt") as apefile:
    for line in apefile:
        doSomething(line)

String methods and/or the csv module might be used here in doSomething(line), but I'll leave that to you so that you can learn.  If you get stuck please ask again, we don't bite :)

Kindest regards.

Mark Lawrence.


More information about the Python-list mailing list