I'm a self taught programmer and im trying to make a ticketing system in Python with csv. However, the reading function doesn't seem to be working after trying out different solutions.
The output I get is:
['Name\tAge\tGender']
[]
['as\t12\tf']
[]
The desired output id like to get is:
Name Age Gender
Jack 25 Male
I've attached the code of this program below. Any help would be greatly appreciated. Thank you.
import sys, select, os, csv
from os import system
def option_1():
with open(input("\nInput file name with .csv extension: "), 'w+') as f:
people = int(input("\nHow many tickets: "))
name_l = []
age_l = []
sex_l = []
for p in range(people):
name = str(input("\nName: "))
name_l.append(name)
age = str(input("\nAge: "))
age_l.append(age)
sex = str(input("\nGender: "))
sex_l.append(sex)
field_names = ['Name', 'Age', 'Gender']
writer = csv.DictWriter(f, fieldnames = field_names, delimiter = '\t')
writer.writeheader()
writer = csv.writer(f, delimiter = '\t')
for row in [p]:
writer.writerow([name, age, sex])
def option_2():
with open(input('Input file name with .csv extension: '), 'a+') as f:
fileDir = os.path.dirname(os.path.realpath('__file__'))
people = int(input("\nHow many tickets: "))
name_l = []
age_l = []
sex_l = []
for p in range(people):
name = str(input("\nName: "))
name_l.append([name])
age = int(input("\nAge: "))
age_l.append([age])
sex = str(input("\nGender: "))
sex_l.append([sex])
writer = csv.writer(f, delimiter = '\t')
for row in [p]:
writer.writerow([name, age, sex])
def option_3():
with open(input("\nInput file name with .csv extension: "), 'r') as f:
fileDir = os.path.dirname(os.path.realpath('__file__'))
f_reader = csv.reader(f)
for row in f_reader:
print(row)
def main():
system('cls')
print("\nTicket Booking System\n")
print("\n1. Ticket Reservation")
print("\n2. Append to an existing file")
print("\n3. Read from an existing file")
print("\n0. Exit Menu")
print('\n')
while True:
option = int(input("Choose an option: "))
if option < 0 or option > 3:
print("Please choose a number according to the menu!")
else:
while True:
if option == 1:
system('cls')
option_1()
user_input=input("\nPress ENTER to return to main menu: \n")
if((not user_input) or (int(user_input)<=0)):
main()
elif option == 2:
system('cls')
option_2()
user_input=input("\nPress ENTER to return to main menu: \n")
if((not user_input) or (int(user_input)<=0)):
main()
elif option == 3:
system('cls')
option_3()
user_input=input("\nPress ENTER to return to main menu: \n")
if((not user_input) or (int(user_input)<=0)):
main()
else:
exit()
if __name__ == "__main__":
main()
When writing data to the file, you explicitly change the default behavior of the csv writer to use tabs as the field delimiter. A similar instruction should be passed to the reader as well, so it knows how to separate between the values in each row. The output you are seeing is a result of the reader's default behavior - it looks for commas to distinguish between each value, but as it finds none, it treats the entire row as a single value, and includes the tab character (\t) as part of the value itself. Instructing the reader to use the same delimiter used for writing the file would allow it to properly parse each field as its own value.
Once the values are properly parsed, you'll notice that the output is still not quite as you desire; the object that is printed in print(row) is actually a list of the items in that row, which is why the output you see now is enclosed with square brackets ([]) for each printed line. Regardless of how the file is stored, you will need to format the output when printing it as required. There are many ways to do so, following is just one possibility:
f_reader = csv.reader(f, delimiter = '\t')
for row in f_reader:
print('\t'.join(row))
According to csv.reader docs:
Each row read from the csv file is returned as a list of strings.
So what you are seeing is the expected behavior. You can join the list of strings with ', '.join(row) if you like.
when i am inserting data first time in csv file it is good
but on second time it again inserts column name
import pandas as pd
name = input("Enter student name")
print("")
print("enter marks info below")
print("")
eng= input("enter English mark : ")
maths= input("enter Maths mark : ")
physics= input("enter Physics mark : ")
chemistry= input("enter Chemistry mark : ")
ip= input("enter Informatic Practices mark : ")
dict = {
"name":{name:name},
"english":{name:eng},
"maths":{name:maths},
"physics":{name:physics},
"chemistry":{name:chemistry},
"ip":{name:ip}
}
df= pd.DataFrame(dict)
df.to_csv("hello.csv", sep="|",index=False,na_rep="null",mode='a')
print("hello.csv")
read = pd.read_csv("hello.csv", sep='|')
print(read)
data in csv file :
name|english|maths|physics|chemistry|ip
dddd|dd|e3|3|3|3
name|english|maths|physics|chemistry|ip
ddddddd|e33|33|3||3
name|english|maths|physics|chemistry|ip
dddddd|33|333||3|
please help in solving how to fix so that column not get added multiple time
you can read the csv file everytime before your run this script.
import pandas as pd
import os
df = pd.DataFrame() if not os.path.exists("hello.csv") else pd.read_csv("hello.csv", sep='|')
name = input("Enter student name")
print("")
print("enter marks info below")
print("")
eng = input("enter English mark : ")
maths = input("enter Maths mark : ")
physics = input("enter Physics mark : ")
chemistry = input("enter Chemistry mark : ")
ip = input("enter Informatic Practices mark : ")
dict = {
"name": {name: name},
"english": {name: eng},
"maths": {name: maths},
"physics": {name: physics},
"chemistry": {name: chemistry},
"ip": {name: ip}
}
df = df.append(pd.DataFrame(dict))
df.to_csv("hello.csv", sep="|", index=False, na_rep="null", mode='w')
print("hello.csv")
read = pd.read_csv("hello.csv", sep='|')
print(read)
and you can also use this code below to export df without columns, but may still have to check file existence or columns sequence first.
df.to_csv('filename.csv', header=False, sep='|', mode='a')
The output file is being opened in append mode, and to_csv() will include the header row by default. You could simply turn off the header:
df.to_csv("hello.csv", header=False, sep="|", index=False, na_rep="null", mode='a')
which will work, but your CSV file will not have a header row. If you require the header then you could check whether the output CSV file already exists and disable headers if it does.
One way is that suggested in the answer by #Eason, however, that might not be practical for large files due to the extra loading time (possibly this is the reason why you are using append mode?)
The following disables the CSV headers if the file already exists and is not empty.
from pathlib import Path
header = True
p = Path('hello.csv')
if p.exists() and p.stat().st_size:
header = False
df.to_csv(p, header=header, sep="|", index=False, na_rep="null", mode='a')
I'm trying to save input data from the terminal in a CSV file. Here is the code
import csv
field = ['Account', 'Name']
rows = []
filename = "db.csv"
with open(filename, 'w') as csvfile:
# creating a csv writer object
csvwriter = csv.writer(csvfile)
csvwriter.writerow(field)
while True:
acc = int(input("Account No: "))
name = input("Enter Name: ")
rows[0] = acc
rows[1] = name
# writing the data rows
csvwriter.writerows(rows)
break
How to save those data in the CSV file?
rows is an empty list you can't use rows[0] and rows[1] like this.
You can use append() method
rows.append(acc)
rows.append(name)
csvwriter.writerows(rows)
or simply
csvwriter.writerows([acc, name])
This works for me:
import csv
field = ['Account', 'Name']
rows = []
filename = "db.csv"
with open(filename, 'w') as csvfile:
# creating a csv writer object
csvwriter = csv.writer(csvfile)
csvwriter.writerow(field)
while True:
acc = int(input("Account No: "))
name = input("Enter Name: ")
# writing the data rows
csvwriter.writerow([acc, name])
keep_going = input("Continue? [y/n]")
if keep_going.lower() == "n":
break
I'm having a little toruble with making this program for my assignment I'm suppossed to search if a pre-registered player appears in the list or not, find the number of a specific player, print a list of players and their information, and use at least one if-else or elif statement. I access the data by importing the "battle_royale.csv" file.
The output of the code is suppossed to look like this:
This is all I have so far:
def main():
avatarNames = [”LarchDew15”,”Pinerain2”,”xOakenMaidx”,”Grandidel”,”Gened123”,”Tufty98”,”silverstar”,”grimRAVEN”,”fogdell”,”111marshglitter111”,
”1337Vale”,”pinesword”,”GreyLore”,”silveneye90””Shaewaith1999”,”ronar”,”yulnul”,”durowen”,”glyrgrim”,”Goghyll55”,
”Welriel21”,”Glanros0000”,”Lochach2000”,”Ashioth”,
”ashrar12”,”immain_321”,”kwelnar”,”Talzak01”,”Lirzen”,”Yoraish555",
”Renryl”,”ghuluith000”,”ryzenfire”,”gryffenford”,”collock”,
”sidwick2005”,”fayrewater”,”beestelonde”,”mucktor1x1”,”dwalegarth”,
”namankol”,”qigomx0x”,”Iderdizan2001”,”bulbascore100”,”enaux0x0x0”,
”yojugo1001”,”sayeon121”,”yabu111”]
playerNames = [”Emily”,”Hannah”,”Madison”,”Jacob”,”Micheal”,”Matthew”,”Ashley”,”Sarah”,”Christopher”,”Alexis”,”Nicholas”,”Samantha”,
”Andrew”,”Javier”,”Caleb”,”Hunter”,”Nicholas”,”Samantha”,”Andrew”,
”Jessica”,”Taylor”,”Daniel”,”Tyler”,”Joshua”,”Elizabeth”,”Billy”,”Olivia”,”Ethan”,”Abigail”,”Emma”,“Alexander”,”Isabella”,”Sophia”,”Xavier”,“Maya”,”Landon”,”Owen”,”Devin”,“Jocelyn”,“Diego”,
“Cody”,”Damian”,”Zoey”,”Sadie”,”Travis”,”Eli”,”Colin”,“Braden”,”Quinn”,”Conner”,”Cassidy”,
”Riley”,”Morgan”,”Javier”,”Caleb”,”Hunter”]
playerNumber = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50]
print(”Welcome to the Battle Royale Game Tournament Registration”)
print(” ****************Main Menu****************”)
options = input(”A: find pre-registered player ; B: Find the number of a specific player ; C: Print lists of player ; Q: Quit/Log out Please enter your choice:”)
main()
I would suggest using pandas, can't go wrong here:
import pandas as pd
df = pd.read_csv("path/to/file.csv", columns=["Avatar_Names", "Player Number"])
if df["Avatar_Names"].isin([avatar_name]):
do_stuff()
However, you can also use the CSV module.
import csv
data = []
with open('file.csv', newline='') as csvfile:
dataset = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in dataset:
data.append(row)
do_stuff_with_data()
I have a csv file in the same directory as my python script. This is a screenshot of the sheet:
The name of the excel file is test_book.csv.
If I use the code below:
import csv
def main():
with open('test_book.csv') as csv_file: # Opens the book
csv_reader = csv.reader(csv_file, delimiter=',')
for idx, row in enumerate(csv_reader): # Looping through each line with a value
if idx > 0:
print("The username is %s, the name is %s and the number is %s" %(row[0], row[1], row[2]))
It gives me:
If I'm looking for a user, I can use the following code:
import csv
def main():
user_choice = input("Please give the number of the user you wish to search for: ")
with open('test_book.csv') as csv_file: # Open the book
csv_reader = csv.reader(csv_file, delimiter=',') # Read the file
for row in csv_reader: # Loop through the book
if row[2] == user_choice: # Row[2] is the third column along - since indexes start at 0
print("The username is %s, the name is %s and the number is %s" %(row[0], row[1], row[2]))
And now I get:
So i have been given a task to develop an employee database and store all information in a CSV file. After adding information i need usable options for removing, editing and searching said data. Its a grey area on what I can and can't import so if there's a method using no porting that would be perfect. Basically, anything just using read() and write().
However, no matter what I do I can't find help online on how to actually pull this specific data in a usable format. Below is how I'm adding it to the CSV file, but no matter what I try I end up wiping the file or just getting errors when I attempt a removal process. Hopefully, whenever I can find a way to pull this data, the edit and search functions will be just a case of logic.
(My Add Function)
def add_employee(): #THIS WORKS
EmployeeID = int(input("Please enter the employee ID here "))
EmployeeName = input("Please enter the name here ")
EmployeeDep = input("Please enter the department here ")
EmployeeDes = input("Please enter the designation here ")
EmployeeStartDate = input("Please enter the start date here in format of DD-MM-YYYY ")
EmployeeStatus = input("Please enter the status here ")
with open('database.csv', "a") as f:
employee_add = ""
employee_add += "%s," % EmployeeID
employee_add += "%s," % EmployeeName
employee_add += "%s," % EmployeeDep
employee_add += "%s," % EmployeeDes
employee_add += "%s," % EmployeeStartDate
employee_add += "%s," % EmployeeStatus
employee_add += "\n"
f.write(employee_add)
print("Added correctly")
continue_or_quit()
I recommed using pandas:
import pandas as pd
Load in your csv file to a dataframe object:
employee_df = pd.read_csv("employee_info.csv")
You can add new rows:
name = "name"
password = "password"
email = "email#domain.com"
# depends on your columns, and the order of them!
employee_df.loc[df.index.max()+1] = [name, password, email]
And then export it to csv again:
employee_df.to_csv("employee_info.csv", index=False)
I actually quite like working with csv's in python using just regular formatting.
things like:
rows = content.split("\n") # get the rows (content in this example would be result of .read()
for row in rows:
values = row.split(",") # get row values
To add a row as per your example you can use something like:
row = "{},{},{},{},{},{}\n".format(EmployeeID, EmployeeName, EmployeeDep, EmployeeDes, EmployeeStartDate, EmployeeStatus)
with open(output, "a") as f:
f.write(row)