read in a list in a file to list

Erik python at lucidity.plus.com
Mon Apr 10 18:35:40 EDT 2017


On 09/04/17 22:22, john polo wrote:
> 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
> 'datObj=datFil.read().replace('" ','').replace('"','')?
>
> datObj2 = datObj2.replace('"','')  #this was here to try to get rid of "
> that didn't have a subsequent space.

John, where does your "apelist.txt" file come from? Who has decided what 
format it should be in?

If *you* get to decide that, then the best thing to do is to specify a 
format that is easy to read in in the first place - rather than 
specifying something that looks like source code and then has to be parsed.

E.g., if the file had the format:

Home sapiens
Pan troglodytes
Gorilla gorilla

(i.e., each value on a separate line with no quotes or any other 
"noise"), then the code to read that in as you have indicated you want 
is something like:

for i in open("apefile.txt").readlines():
     print("one of the apes is " + i.rstrip())

(the .rstrip() is to remove the trailing newline character - and any 
other trailing whitespace - which readlines() will include in what it 
returns).

Of course, if you don't have any control over the input file's format, 
then it looks like you (or something you delegate to) will have to do 
some sort of parsing.

E.


More information about the Python-list mailing list