python_写⼊csv⽂件时候⽆法进⾏原样写⼊(写⼊字符串中出现逗号,时候,csv⽂件⾃。。。
问题描述:
写⼊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
python怎么读csv数据# 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]])
参考:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。