0

So I have to take a .csv file (which can be downloaded clicking this: http://ge.tt/7lx5Boj2/) and I want to convert it into a 2D list.

My code currently does so, but with one problem.

Each element of the nested list is being read as a big string rather than a list of elements because an apostrophe is being added at the beginning and end of each nested list.

For example, rather than:

["ID","Name","Type 1","Type 2","Generation","Legendary"]

I am getting:

['"ID","Name","Type 1","Type 2","Generation","Legendary"']

To resolve this, I tried to make a nested for loop to replace every apostrophe in the list with an empty character but my code doesn't do anything. It just prints the exact same string as if the replace operation never happened.

def read_info_file(filename):
        opened_infocsv = open(filename, 'r') #opens an argued .csv file with INFO ormat.
        linebylinelist = [fline.splitlines() for line in opened_infocsv] #converts entire .csv into a 2D list
        opened_infocsv.close()

        print(linebylinelist)
        print('\n')

        for i in linebylinelist:
            for l in i:
                l.replace("'","")

        print(linebylinelist)

    read_info_file('info_file5.csv')

Any ideas on fixing this? NOTE: I am not allowed to import CSV

EDIT : I tried changing .replace to .strip and it still doesn't work. I honestly have no idea how to fix this.

I believe the root of the problem has to do with the way in which I converted the CSV into a 2d list using list comprehension. Maybe it is possible to convert a CSV into a 2d list without converting the lines to strings first.

ruckarucka
  • 41
  • 2
  • 11

2 Answers2

0

str.replace does not change current string - it returns a copy of the string with all occurrences of substring old replaced by new. You should assign the result of the function to the current list item.

for i in linebylinelist:
    for kk,ss in enumerate(i):
        i[kk] = ss.replace("'","")
napuzba
  • 6,033
  • 3
  • 21
  • 32
  • I'm not familiar with the notation "ss,kk". Could you explain what this is doing? Also, is there anyway to replace directly in place? I'm also getting an "int object has no attribute 'replace'" error. – ruckarucka Apr 23 '17 at 17:58
  • Thank you for the link but the solution you posted is not working. – ruckarucka Apr 23 '17 at 21:30
0

use the csv module to read a csv file.

Also, to open a file, use a context manager. As an example, see below code.

import csv
filename = 'info_file5.csv'
with open(filename, 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
MSKW
  • 55
  • 3
  • 7