簡體   English   中英

在Python 3中將CSV文件追加到新的CSV文件時,單詞之間出現不必要的“”

[英]Getting unwanted “ ” between words when appending a CSV file to a new CSV file in Python 3

我正在嘗試將CS​​V文件追加到新的CSV文件,並且在我的第一個文檔中的單詞之間沒有“”的地方,將其追加到新文件時得到了這些。 范例:

house
building 
apartment
loan 

我要如何導入CSV文件。 我寫了這段代碼:

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()

CSV的結果是這樣的:

"house
"
"building
"

等等…

我如何擺脫那些煩人的“”? 我完全不知道…

我不確定這是否是原因,但是我認為這是因為您要將行變成csv_file_writer.writerow([row])行中的列表,我將在下面使用它:

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)

您可以將csv.writer設置為不使用引號= csv.QUOTE_NONE進行引用,如下所示:

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()

演示鏈接:

https://repl.it/repls/FarLopposedBaitware

替換行:

document_to_append = open("test.csv", "r")

通過:

document_to_append = [line.rstrip() for line in open('test.csv', "r")]

注意:這將起作用,但是您必須刪除以下行: document_to_append.close(),因為document_to_append不再是句柄,而是列表。

如果您想以任何方式關閉文件,請執行以下操作,而不是列表理解(上述解決方案):

with open('test.csv') as f:
    document_to_append = [line.rstrip() for line in f]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM