I'm trying to append a CSV file to a new CSV file, and where there were no "" between the words in my first document, i get those when appending it to the new file. Example :
house
building
apartment
loan
is how is the CSV file I want to import. I wrote this code :
import csv
csv_file = open("bigcsv.csv", "a", encoding='utf-8', newline = "")
csv_file_writer = csv.writer(csv_file, delimiter= ",")
document_to_append = open("test.csv", "r")
for row in document_to_append:
print(row)
csv_file_writer.writerow([row])
document_to_append.close()
csv_file.close()
And the result in CSV is this :
"house
"
"building
"
and so on…
How can I get rid of those annoying ""? I have absolutely no idea…
I'm not sure if this is the reason, but I think it's because you're turning row into a list in the line csv_file_writer.writerow([row])
I'd use this below:
import csv
with open("bigcsv.csv", "r") csv_file:
with open("test.csv", "w") as csv_file_writer:
for row in csv_file:
csv_file_writer.writerow(row)
You can set the csv.writer to quote nothing with quoting=csv.QUOTE_NONE like below:
import csv
csv_file = open("bigcsv.csv", "a", encoding='utf-8', newline = "")
csv_file_writer = csv.writer(csv_file, delimiter= ",", escapechar=' ',quoting=csv.QUOTE_NONE,lineterminator='')
document_to_append = open("test.csv", "r")
for row in document_to_append:
print(row)
csv_file_writer.writerow([row])
document_to_append.close()
csv_file.close()
Demo Link:
replace the line:
document_to_append = open("test.csv", "r")
by:
document_to_append = [line.rstrip() for line in open('test.csv', "r")]
Note: this will work but you would have to remove the line: document_to_append.close() as document_to_append is no longer a handle, but a list.
If you want to close the file anyhow, then instead of list comprehension(the above solution), do this:
with open('test.csv') as f:
document_to_append = [line.rstrip() for line in f]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.