-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?

3
  • 2
    What's with the if x == '*'? Of course the string doesn't contain ' if it's literally * Commented Sep 16, 2022 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) Commented Sep 16, 2022 at 11:46
  • Does this answer your question? Using python csv writer without quotations Commented Sep 16, 2022 at 11:49

1 Answer 1

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(","))
Sign up to request clarification or add additional context in comments.

6 Comments

The if is still pointless, "*".replace("'", "") simply returns "*"
NameError: name 'lines' is not defined unfortunately this error I am getting
@tripleee I have let it although yes it doesn't have much use here
@MKR I added code for to read the lines. I removed the split(",") as you don't need to split your string I believe
Still doesn't work. Now I have the string split between every column.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.