-2

Hey guys I wanted to code a little program, and I have this code

inputfile = csv.reader(open('data.csv','r'))
for row in inputfile:

but now I have the problem, that I have commas and : in my CSV and I want to replace the ':' with a comma, because I want to read it in with the row[3] function for example. Or is it possible without replacement? thank you guys!

inputfile = csv.reader(open('data.csv','r'))
for row in inputfile:
    xyc = row[0]
    afs = row[1]
    yxcva = row[2]
    asdfe = row[3]

I tried that already:

data = ""

with `open("input.csv")` as file:
     data = file.read().replace(":", ",")

with `open("data.csv")` as file:
     file.write(data)
tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • 3
    Please provide sample input and the expected result. It's not clear if you want to edit the original file, or simply need a way to parse each line into four fields. – chepner Mar 05 '20 at 13:44
  • Do you actually want to re-write the file, or just read it properly? Either way, use the `delimiter` paramter of `reader`. – tobias_k Mar 05 '20 at 13:45
  • 1
    Or do you mean the CSV file uses _both_ `,` and `:` as delimiter? On the same line, or on different lines? Does the file hold string data that might itself contain a `,` or `:`? – tobias_k Mar 05 '20 at 13:47
  • Does this answer your question? [Python CSV change separator](https://stackoverflow.com/questions/45256104/python-csv-change-separator) – Askold Ilvento Mar 05 '20 at 13:50
  • if it could use both (, and :) as delimiter that would be fine too sample input in data.csv abs,jkel,dheu:kljsk:3234:2324 sample output in another file abs,jkel,dheu,kljsk,3234,2324 – Elias Grabherr Mar 05 '20 at 13:52

1 Answers1

0

If you use the a for loop like that and you want to split the line, you can do something like

elements = row.split(',')
xyc = elements[0]
abc = elements[1]
...

The parameter in the split command tells the method which char to use to do the split !

Kuzniarz
  • 60
  • 1
  • 11