简体   繁体   English

Python 错误地写入 csv 文件

[英]Python writes into csv file, incorrectly

I tried my code in Mac, and it is ok, but in windows, python does not write my list correctly into a CSV file, and some data is written in different rows while it should be written in the same row.我在 Mac 上尝试了我的代码,它没问题,但是在 Windows 中,python 没有正确地将我的列表写入 CSV 文件,并且一些数据被写入不同的行而应该写入同一行。

personel = [firstname, lastname, detail]
with open("hr.csv", "a", newline='', encoding="utf-8") as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(personel)

I wrote a test program with your code (on Windows 10) and didn't find a problem with the CSV output.我用您的代码(在 Windows 10 上)编写了一个测试程序,但没有发现 CSV 输出有问题。 Run this on your machine and see what happens.在你的机器上运行它,看看会发生什么。

This is the test output (it consists of random letters):这是测试输出(它由随机字母组成):

fziziszaoq,gxlcgmncdn,bjehjbcjgq
lrzzbujdru,bxxqkavqro,mktmygqmrc
mauzgqkgqw,uijnzavbyi,jhjqxkbran
oplrispslo,irvkjgcimm,kjbfbpilmi
regaajxhdf,wwtyyspuoi,icmrcjwswx

This is the test code:这是测试代码:

import csv
import random
import string

def randomString(stringLength=10):
    letters = string.ascii_lowercase
    return ''.join(random.choice(letters) for i in range(stringLength))

x = 0
while(x < 5):
    personel = [randomString(), randomString(), randomString()]
    with open("hr.csv", "a", newline='', encoding="utf-8") as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(personel)
    x = x + 1

My suspicion is that your inputs contain newlines.我怀疑您的输入包含换行符。 Check that there are not stray newline characters in firstname , lastname , or detail.检查firstnamelastnamedetail.是否没有杂散的换行符detail.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM