read in a list in a file to list
jpolo at mail.usf.edu
Sun Apr 9 17:22:25 EDT 2017
On 4/8/2017 3:21 PM, breamoreboy at gmail.com wrote:
> On Saturday, April 8, 2017 at 7:32:52 PM UTC+1, john polo wrote:
>> 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)
>> 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
> I'll start you off.
> with open("apefile.txt") as apefile:
> for line in apefile:
> 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.
Thanks for the reply. I looked back through the methods for strings. I
also looked at the csv module, but I couldn't tell which one of those
would help. The small .txt file does have commas, but with the weird
form of listname =  , , , etc. for a .csv, I don't know how
that would be read in a like a .csv. But now that I think about it,
datObj2 in my script prints just the list elements, so maybe the
'listname=' part wouldn't affect it...
Anyway, after reviewing string methods some more, I came up with this.
If I understood your hint, the loop was supposed to somehow break up the
long string that came from the apelist file, but it seemed that trying
to use the split method in a loop wouldn't work, especially since one of
my attempts started a list and then the interpreter said there were no
split methods for list.
The new attempt gives me a list, now I have to figure out how to deal
with unwanted quotation marks and spaces.
datFil = open("apelist.txt")
datObj = datFil.read()
datObj2 = datObj.replace('" ','') #added this comment while writing
this email: I guess I could have used 'datObj = datFil.read().replace('"
','')'. Can you make two replacements in the same statement, for example
datObj2 = datObj2.replace('"','') #this was here to try to get rid of "
that didn't have a subsequent space.
datObj2 = datObj2.split(',')
for i in datObj2:
print("one of the apes is " + i)
['Homo sapiens', ' Pan troglodytes', ' Gorilla gorilla']
one of the apes is Homo sapiens
one of the apes is Pan troglodytes
one of the apes is Gorilla gorilla
Per reply of Rick Johnson, I altered variable names to something generic.
Thanks for the prodding from the replies.
More information about the Python-list