'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:
How many records 1 what is the name of the student ahmad grade ? 3 res [ahmad , 3]
The csv file looks like this:
a,h,m,a,d,
,3
I want it like that:
ahmad
3
Solution 1:[1]
csv.writerow() takes a list of values for that row - you are supplying single values. Strings are iterables - if you give one string to csv.writerow() it will use every single letter as 1 column. You could fix that supplying it as 1 element list:
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.
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:
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:
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:
ABC,5
BCD,7
CDE,42
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
