gpt4 book ai didi

python - csv writer 在每一行周围加上引号

转载 作者:太空狗 更新时间:2023-10-30 02:30:22 25 4
gpt4 key购买 nike

我正在尝试将具有相同格式的多个 csv 文件合并为一个文件。

merge_list = glob.glob(gndlbsum+"*gndlbsum.csv")
filewriter_lbsum = target_dir+"gndlbsum_master.csv"

#get the list of csv files and set the output file
counter=0
for file in merge_list:
with open(file,"rU") as csv_file:
filereader = csv.reader(csv_file)
with open(filewriter_lbsum,"a") as f:
writer = csv.writer(f, delimiter = "|")
#check to see if it's the first file, if it is, add header,
#otherwise skip first row
if counter<1:
for row in filereader:
writer.writerow(row)
counter+=1
else:
header = next(filereader,None)
for row in filereader:
writer.writerow(row)

当我这样做时,输出 csv 中的每一行都完全用双引号引起来,我尝试使用 list.append(row) 代替,但这没有区别,因为行用双引号括起来。有没有办法避免这种情况?

编辑:

这是源文件的示例:

COL1|COL2|COL3
1|2|3
4|5|6

输出:

"COL1|COL2|COL3"
"1|2|3"
"4|5|6"

最佳答案

我认为这将消除由于没有告诉正在创建的 csv.reader 输入文件中的分隔符是 "|" 而引起的引号> 个字符,而不是默认的 "," 个字符。

merge_list = glob.glob(gndlbsum + "*gndlbsum.csv")
file_writer_lbsum = os.path.join(target_dir, "gndlbsum_master.csv")

# Append each csv file in the list to the output file
first_file = True
for file in merge_list:
with open(file, "rU") as csv_file:
reader = csv.reader(csv_file, delimiter="|")
with open(file_writer_lbsum, "w" if first_file else "a") as f:
writer = csv.writer(f, delimiter="|")
# Unless it's the first file, skip its header row
if not first_file:
next(reader)
first_file = False
writer.writerows(reader)

关于python - csv writer 在每一行周围加上引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27551627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com