0

my goal is to create several lists out of the contents of several files. In the past, I have used '{}'.format(x) inside of loops as a way to change the paths inside the loop to match whichever item in the list the loop is working on. Now I want to extend that to appending to lists outside the loop. Here is the code I am using currently.

import csv
import os

c3List = []
c4List = []
camList = []
plantList = ('c3', 'c4', 'cam')

for p in plantList:
    plantFolder = folder path
    plantCsv = '{}List.csv'.format(p)
    plantPath = os.path.join(plantFolder, plantCsv)
    with open(plantPath) as plantParse:
        reader = csv.reader(plantParse)
        data = list(reader)
        '{}List'.format(p).append(data)

But this is giving me AttributeError: 'str' object has no attribute 'append'

if I try to make a variable like this

pList = '{}List'.format(p)
pList.append(data)

I get the same error. Any advice would be appreciated. I am using Python 3.

merpirate
  • 11
  • 3
  • 1
    `str.format()` returns a _string_, which doesn't have a `.append()`. You can't reference a variable simply by creating a string of its name – Pranav Hosangadi Dec 17 '21 at 22:39
  • This might be related to your problem: [How do I create a variable number of variables](//stackoverflow.com/q/1373164/843953) – Pranav Hosangadi Dec 17 '21 at 22:40
  • I want the first time it loops through for it to take the items in c3List.csv and add it to c3List, then c4List.csv and add to c4List, then camList.scv and add to camList. I will look at the variable link you provided and see what I can find there. – merpirate Dec 17 '21 at 22:43
  • 1
    Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – MisterMiyagi Dec 20 '21 at 15:36

1 Answers1

0

Because list object are mutable, you could create a dict referencing all of your lists.

For example with this:

myList = []
myDict = {"a": myList}

myDict["a"].append("appended_by_reference")
myList.append("appended_directly")

print(myList)

you will get ['appended_by_reference', 'appended_directly'] printed.

If you want to learn more about mutability and immutability in python see link.

So my own implementation to achieve your goal would be:

import csv
from pathlib import Path

c3List = []
c4List = []
camList = []
plantList = {'c3': c3List, 'c4': c4List, 'cam': camList}

plantFolder = `folder path`
for p in plantList:
    plantCsv = f'{p}List.csv'
    plantPath = Path(plantFolder, plantCsv)
    with open(plantPath) as plantParse:
        reader = csv.reader(plantParse)
        data = list(reader)
        plantList[p].append(data)

Note: I used an fstring to format the string and pathlib to define filepaths

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
WildSiphon
  • 110
  • 1
  • 6