I have some problems:
I created a csv file
with open('file.csv','a') as f:
thewriter=csv.writer(f)
thewriter.writerow({' name',' adult','child','reference'})
thewriter.writerow([name,ad,ch,ref])
when I run and enter some date for name, adult, child and reference I get the data under different columns. for instance the name column has number rather than the number.
any idea why is that? see the attachment for output in csv file.
obviously that is what the values for ad
, ch
and ref
names are... We cannot tell what is going on without seeing that part of your code
also note that {' name',' adult','child','reference'}
is a set
, i.e. unordered container. Use a list or a tuple e.g. ['name','adult','child','reference']
in addition - do you really want to repeat the header above each data row?
Also note that when using csv module on Windows, you need to supply newline=''
argument to open(). Not doing so result in extra blank line visible after each header/data row
(Jan-30-2020, 10:36 AM)buran Wrote: [ -> ]obviously that is what the values for ad
, ch
and ref
names are... We cannot tell what is going on without seeing that part of your code
also note that {' name',' adult','child','reference'}
is a set
, i.e. unordered container. Use a list or a tuple e.g. ['name','adult','child','reference']
in addition - do you really want to repeat the header above each data row?
Also note that when using csv module on Windows, you need to supply newline=''
argument to open(). Not doing so result in extra blank line visible after each header/data row
Thanks. That is useful. Can let me know how to not repeat header above each data row?
create the header only once. don't write it with every data row. In addition, you may look at (and use csv.DictReader, which has specual method writeheader(). You may also use writerows() to write multiple rows with one line statement
Somehow I am getting errors for creating header only once.
The error is [Errno 13] Permission denied
show your code, however the error suggest you try to open same file for a second time, while it is still open
import pickle
import csv
with open('file.csv','a',newline="") as f:
thewriter=csv.writer(f)
thewriter.writerow([' name',' adult','child','reference'])
ref=-1
av_seats=152
while True:
ad=int(input("Enter a adult "))
ch=int(input("Enter a children "))
name=input("Plese enter your name")
totoal=ad+ch
av_seats=av_seats-totoal
ref=ref+1
thewriter.writerow([name,ad,ch,ref])
print("left are ",av_seats)
op=input("press 'n' to terminate or any key to stop ").lower()
if op=='n':
break
Lines 10-32 need to be indented one kevel, so that they are inside the with
contex manager