read in a list in a file to list
boB Stepp
robertvstepp at gmail.com
Sat Apr 8 17:27:39 EDT 2017
On Sat, Apr 8, 2017 at 3:21 PM, <breamoreboy at gmail.com> wrote:
> 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()
I think you misunderstand what the read() method is doing here. It
does not return a list. Instead, it returns the entire file as a
single string.
>> for ape in apelist:
So here despite the variable name you chose, you are acutally
iterating over the entire file contents character by character. See
Mark's answer/hint below on how to iterate over the file contents by
line. You might want to look up the docs on how to use these file
objects and their methods.
>> 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 :)
--
boB
More information about the Python-list
mailing list