简体   繁体   English

尝试从输入写入 csv,csv output 文件显示每个名称,字母之间有冒号,1 行为空行

[英]Trying to write to csv from input , csv output file shows each name with colons between letters and emtpy line in 1 row

import csv 
n = int(input("How many records ?"))
b = 0
for i in range(n):


   s = input("what is the name of the student  ")
   g = input(" grade ?")
   k.append(s),k.append(g)
 print("res",'[%s]'%', '.join(map(str, k)))

StuGrade = "StuGrade.csv"
with open(StuGrade, 'w' ) as f :
    thewriter = csv.writer(f)
    thewriter.writerow( k[0])
    for i in range(n*2-1) :
        b=b+1
        thewriter.writerow( k[b])
  

This is the output of my program:这是我程序的 output:

 How many records 1 what is the name of the student ahmad grade? 3 res [ahmad, 3]

The csv file looks like this: csv 文件如下所示:

a,h,m,a,d,艾哈迈德,

,3 ,3

I want it like that:我想要这样:

ahmad艾哈迈德
3 3个

csv.writerow() takes a list of values for that row - you are supplying single values. csv.writerow()获取该行的值列表 - 您提供的是单个值。 Strings are iterables - if you give one string to csv.writerow() it will use every single letter as 1 column.字符串是可迭代的——如果你给csv.writerow()一个字符串,它将使用每个字母作为 1 列。 You could fix that supplying it as 1 element list:您可以修复将其作为 1 个元素列表提供的问题:

 thewriter.writerow( [ k[b] ] )  # 1 element list

To write a csv correctly (with single or with multiple values per row and multiple rows) you are missing a newline="" when opening the file (this is well documented) to create the csv file correctly - missing this introduces the empty line in your current output.要正确写入 csv(每行有单个值或多个值和多行),您在打开文件时缺少newline="" (这有据可查)以正确创建 csv 文件 - 缺少它会引入空行您当前的 output。

with open(StuGrade, 'w', newline = "") as f :  # add  newline = ""

You do not really need a csv writer to create a file with 1 thing per line:您实际上不需要 csv 编写器来创建每行包含 1 个内容的文件:

with open("file.txt","w") as f:
    for word in k:               # dont use index iterating, use element itering
        f.write(word + "\n")

would do it.会做的。


Fix/Demo for 2 values per line:每行 2 个值的修复/演示:

import csv 

k = ["ABC","5", "BCD","7", "CDE","42"]

StuGrade = "StuGrade.csv"
with open(StuGrade, 'w', newline = "") as f :  # added newline
    thewriter = csv.writer(f)

    # go over the range of input indexes and increase by 2       
    for idx in range(0, len(k), 2):
        # slice and write 2 values as 2 columns from your k list at once 
        thewriter.writerow( k[idx : idx+2]) 

print(open("StuGrade.csv").read())

Output: Output:

ABC,5
BCD,7
CDE,42

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

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