[Tutor] Extract Field from List
Peter Otten
__peter__ at web.de
Sun Aug 8 10:32:06 EDT 2021
On 08/08/2021 15:48, Stephen P. Molnar 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?
(1) Your CSV is tab-delimited
(2) There is only one row
Try
with open(...) as csvfile:
rows = csv.reader(csvfile, delimiter='\t')
[data] = rows
This ensures that there is only one row so that no data can be lost
accidentally. Note that data will be a tuple; convert it if necessary.
More information about the Tutor
mailing list