[Tutor] Extract Field from List
David
bouncingcats at gmail.com
Sun Aug 8 10:36:33 EDT 2021
On Sun, 8 Aug 2021 at 23:49, Stephen P. Molnar <s.molnar at sbcglobal.net> wrote:
>
> I have hit a roadblock in a Python script I have been developing to
> process a large number of text files of fixed format.
>
> I have a list of names of chemicals, which I can read into a list.csv:
>
> CaffeicAcid,Cannflavin-A,Cannflavin-B,Cannflavin-C,Diosmetin,Echinacoside,Hesperetin,L-CichoricAcid
>
> My code is;
>
> import csv
>
> with open("Ligand.list_r.txt", newline='') as csvfile:
> rows = csv.reader(csvfile, delimiter = ',')
> data = []
> for rows in rows:
> data.append(rows)
>
> print(data)
>
> This results in:
>
> [['CaffeicAcid\tCannflavin-A\tCannflavin-B\tCannflavin-C\tDiosmetin\tEchinacoside\tHesperetin\tL-CichoricAcid']]
>
> when run.
>
> What I need to do is iterate through the list and generate names of the
> format of chemicalname+'.i.log'.
>
> This is where I can seem to hit a show stopper. How do I extract fields
> form the list generated by the script that works? What am I missing?
There's several reasons why your code does not give the result you want.
You also don't give any clue which version of Python you are using.
Python behaviour does differ between versions, so it is always
important to mention that. Just run 'python --version' if you are on Linux.
Debugging this code might be tricky for you because
modern csv.reader() returns a generator object, not a list.
So, I suggest as a learning exercise you replace the line:
rows = csv.reader(csvfile, delimiter = ',')
with
rows = list(csv.reader(csvfile, delimiter = ','))
That means that rows will become a list object, which is what older
versions of Python used to do, and doing that will make it much
easier for you to see what is happening in your code.
After that, you can debug your code by sprinkling a few print statements
around it so that you can see the data in the variables.
For example:
print("data = ", data)
Then, you will be able to see what the code is doing. And you might be
able to debug it yourself. Let us know how it goes.
More information about the Tutor
mailing list