BaconCatBug
BaconCatBug

Reputation: 195

How to apply regex sub to a csv file in python

I have a csv file I wish to apply a regex replacement to with python.

So far I have the following

reader = csv.reader(open('ffrk_inventory_relics.csv', 'r'))
writer = csv.writer(open('outfile.csv','w'))
for row in reader:
    reader = re.sub(r'\+','z',reader)

Which is giving me the following error:

Script error: Traceback (most recent call last):
  File "ffrk_inventory_tracker_v1.6.py", line 22, in response
    getRelics(data['equipments'], 'ffrk_inventory_relics')
  File "ffrk_inventory_tracker_v1.6.py", line 72, in getRelics
    reader = re.sub(r'\+','z',reader)
  File "c:\users\baconcatbug\appdata\local\programs\python\python36\lib\re.py",
line 191, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object

After googling to not much luck, I would like to ask the community here how to open the csv file correctly so I can use re.sub on it and then write out the altered csv file back to the same filename.

Upvotes: 0

Views: 1497

Answers (2)

Ajax1234
Ajax1234

Reputation: 71451

csv.reader(open('ffrk_inventory_relics.csv', 'r')) is creating a list of lists, and when you iterate over it and pass each value to re.sub, you are passing a list, not a string. Try this:

import re
import csv
final_data = [[re.sub('\+', 'z', b) for b in i] for i in csv.reader(open('ffrk_inventory_relics.csv', 'r'))]
write = csv.writer(open('ffrk_inventory_relics.csv'))
write.writerows(final_data)

Upvotes: 1

zipa
zipa

Reputation: 27869

If you don't need csv you can use replace with regular open:

with open('ffrk_inventory_relics.csv', 'r') as reader, open('outfile.csv','w') as writer:
    for row in reader:
        writer.write(row.replace('+','z'))

Upvotes: 0

Related Questions