问题描述:
写入csv文件时候无法进行原样写入(写入字符串中出现逗号","时候,csv文件自动分成两个单元格)
with open("test.csv","w") as f:
f.write("闲暇时,我会被一段,配乐诗朗诵,所感动,悲伤")
print("写入成功")
原因分析:
在写入csv文件的时候英文逗号在csv中被默认为单元格的分隔。
前两个逗号是中文的逗号,后面两个英文的逗号被默认为分隔,写入了不同的单元格中。
解决方案:
使用csv模块
import csv
with open("test.csv", "w") as f:
writer = csv.writer(f)
writer.writerow(["闲暇时,我会被一段,配乐诗朗诵", ",所感动", ",悲伤"])
结果显示,英文逗号成功被写入了csv文件中!!!
也可以在with open 的语句中加入 newline=""来确保每次写入数据后,只回车一次
import csv
with open("test.csv", "w") as f:
writer = csv.writer(f)
writer.writerow(["闲暇时,我会被一段,配乐诗朗诵", ",所感动", ",悲伤"])
writer.writerow(["闲暇时,我会被一段,配乐诗朗诵", ",所感动", ",悲伤"])
# 写入多行用writerows
# writer.writerows([[0, 1, 3], [1, 2, 3], [2, 3, 4]])
import csv
with open("test.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["闲暇时,我会被一段,配乐诗朗诵", ",所感动", ",悲伤"])
writer.writerow(["闲暇时,我会被一段,配乐诗朗诵", ",所感动", ",悲伤"])
# 写入多行用writerows
# writer.writerows([[0, 1, 3], [1, 2, 3], [2, 3, 4]])
参考:
https://blog..net/waple_0820/article/details/70049953
https://www..com/meitian/p/4625011.html