-4

I managed with converting the txt file to .csv with python.

However, now I don't know how to remove the quotes enclosing all strings in my CSV file.

enter image description here

I tried the following code:

 import csv

 with open('UPRN.txt', 'r') as in_file:
 stripped = (line.strip() for line in in_file)
 lines = (line.split(",") for line in stripped if line)
 with open('UPRN.csv', 'w', newline='') as out_file:
    writer = csv.writer(out_file)
    writer.writerow(('Name', 'UPRN','ADMIN_AREA','TOWN','STREET','NAME_NUMBER'))
    writer.writerows(lines)
    for lines in writer:
        lines = [x.replace("'","") if x == '*' else x for x in row]
        writer.writerow(lines)

but I am getting an error:

TypeError: '_csv.writer' object is not iterable

The easiest way could be:

Remove quotes from String in Python

but the CSV writer has no attributes like write, replace, etc. '_csv.writer' object has no attribute 'write'

Moreover, I am not sure if a wildcard is needed here:

Python wildcard search in string

Is there any quick way of removing the quotes when the CSV module is imported?

Geographos
  • 827
  • 2
  • 23
  • 57
  • 2
    What's with the `if x == '*'`? Of course the string doesn't contain `'` if it's literally `*` – tripleee Sep 16 '22 at 11:46
  • you are iterating over your csv writer, instead of the lines. should be something like `for line in lines:` then `line = [element.replace("'", "") for element in line]` and `writer.writerow(line)` – Jeanot Zubler Sep 16 '22 at 11:46
  • Does this answer your question? [Using python csv writer without quotations](https://stackoverflow.com/questions/23882024/using-python-csv-writer-without-quotations) – fsimonjetz Sep 16 '22 at 11:49

1 Answers1

1

I think you should rather iterate on your lines list,

with open('UPRN.txt', 'r') as in_file:
    lines = [line.strip().replace("'","") for line in in_file]

with open('UPRN.csv', 'w', newline='') as out_file:
    writer = csv.writer(out_file)
    writer.writerow(('Name', 'UPRN','ADMIN_AREA','TOWN','STREET','NAME_NUMBER'))

    for line in lines:
        writer.writerow(line.split(","))
PlainRavioli
  • 1,127
  • 1
  • 1
  • 10