How do i read from a csv file I created - python

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.

Related

writing to existing CSV file and saving its data

I'm creating a program for online shop and I have problems with rewriting on the csv file of the users registration. I create the file and put headers(as list of information that I want).
I'm having problem with adding the new users. Every time when I run the program, enter all the information for the user, the csv file rewrites the user.
Could you help? I've tried everything, but it doesn't work...
Here is the code.
Please excuse me, I'm new to programming :)
header = ['ID', 'First Name', 'Last Name', 'Email', 'Phone', 'Date Registered', 'Password']
with open('users.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(header)
f.close()
new_user = []
user_id = 0
print(f" Welcome to the new online shop! \n")
print(f" You will need registration to enter.\n If you don't have please enter 0. \n "
f"If you already have - please enter 1.\n For ADMIN menu - please enter 9")
class UserId:
def __init__(self, id_user, new_user_fn,
new_user_ln, new_user_em,
new_user_phone, _new_user_pas,
new_user_date_reg):
self.id_user = id_user
self.new_user_fn = new_user_fn
self.new_user_ln = new_user_ln
self.new_user_em = new_user_em
self.new_user_phone = new_user_phone
self.new_user_date_reg = new_user_date_reg
self._new_user_pas = _new_user_pas
def user_registration():
now = datetime.now()
dt = now.strftime("%d/%m/%Y %H:%M:%S")
print(f" Enter your First name: ")
new_user_fn = str(input()).upper()
print(f" Enter your Last name: ")
new_user_ln = str(input()).upper()
print(f" Enter your email: ")
new_user_em = input().upper()
print(f" Enter your phone number: ")
new_user_phone = str(input())
new_user_date_reg = dt
print(f" Enter your password: ")
new_user_pas = str(input())
new_user.append(user_id + 1)
new_user.append(new_user_fn)
new_user.append(new_user_ln)
new_user.append(new_user_em)
new_user.append(new_user_phone)
new_user.append(new_user_date_reg)
new_user.append(new_user_pas)
with open("users.csv", 'a+', newline="") as e:
writer1 = csv.writer(e)
writer1.writerow(new_user)
e.close()
It looks like your problem is here
with open('users.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(header)
f.close()
By using the 'w' you are telling the program to always create a new file.So you must use 'a' instead of 'w' as you want to append to a file and not overwrite it.
Also with with open you don't need to use f.close() as with open automaticaly closes and saves the file
So the code shoud look like this
with open('users.csv','a') as f:
writer = csv.writer(f)
writer.writerow(header)
What you can do is test if your file exists :
fileName = 'users.csv'
if not os.path.exists(fileName):
with open(fileName, 'w') as f:
writer = csv.writer(f)
writer.writerow(header)
Notes :
1- using ´with’ means you do not need to close the file. All cleaning is done when exiting the inner code
2- using variable for file name variable is good so you are sure to always use the same file name; and when you have to modify it, then do it in one place.

Create a function to search for a Composer by name in the dataset

Guys just a bit stuck with my code..if someone can help me i'd really appreciate it
Q1.Create a function to search for a Composer by name in the dataset. Since a Composer could exist multiple times, the function should return a list of the appropriate "BL record IDs" related to the Composer.
import csv
def searchname(userdata):
with open('bl_printed_music_500.csv', newline='', encoding="utf-8-sig") as csvfile:
reader = csv.DictReader(csvfile)
found = False
for row in reader:
if row['Composer']==userdata:
found = True
return list()
print(result)
uinput = input('Search for Composer: ')
searchname(uinput)
Just change 'n' to be the column where you'd find the composer name. You also might need to normalize capital/non-capital letters since you're dealing with user inputs ...
Also, I just output the entire row of data, you can specifically add what you want to your list if the file has too much data.
def searchname(userdata):
list = []
for line in open('bl_printed_music_500.csv', 'r'):
row = line.split(',')
if row[n] == userdata:
list.append(line)
return(list)
uinput = input('Search for Composer: ')
print(searchname(uinput))
You should create empty list before for-loop. And inside for-loop you should append() row (or row["ID"]) to this list. And later you should return this list.
And you shouldn't use print() after return because it will be never executed because return exits functions at once.
def searchname(userdata):
results = list()
with open('bl_printed_music_500.csv', newline='', encoding="utf-8-sig") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if row['Composer'] == userdata:
results.append(row)
return results
# --- main ---
uinput = input('Search for Composer: ')
results = searchname(uinput)
print(results)
BTW:
Sometimes it is good to convert to lower() or upper() to correctly compare strings
if row['Composer'].lower() == userdata.lower():
because strings can be in different size.
Sometimes it is good to check if string is only part of other string
if userdata.lower() in row['Composer'].lower():
because user may give only part of name.
Sometimes text may have whitespaces (spaces, tabs, enters) at the ends of string and it is good to remove it using strip()
if userdata.strip().lower() in row['Composer'].strip().lower():
def searchname(userdata):
results = list()
with open('bl_printed_music_500.csv', newline='', encoding="utf-8-sig") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if userdata.strip().lower() in row['Composer'].strip().lower():
results.append(row)
return results
# --- main ---
uinput = input('Search for Composer: ')
results = searchname(uinput)
print(results)

CSV files, creating lists from a CSV file, and perform a search for data

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:

Transfering specific rows from one cvs file to another cvs file

So, I'm trying to transfer rows[0,1,2,9,10] from what I've designated as "e_file" to "no_file"
When I print "data" I am given the exact information I want, I was just wondering how I should proceed with transferring this data to a corresponding CSV file?
Thank you.
e_file = '/Users/massive/Desktop//NO/hour.csv'
no_file = '/Users/massive/Desktop/NO/combined.csv'
with open(e_file,'r') as e_r:
state_code = input("Enter state code: ")
county_code = input("Enter county code: ")
station_number = input("Enter station number: ")
csv_reader_2 = csv.reader(e_r)
for row in csv_reader_2:
if row[0] == str(state_code).zfill(2) and row[1] ==str(county_code).zfill(3) and row[2] == str(station_number).zfill(4):
data = [row[0],row[1],row[2],row[9],row[10]]
print(data)
Maybe something like (I cannot test it unless you provide a working example):
with open(newFile, 'wb') as csvfile:
fwriter = csv.writer(csvfile)
for line in data:
fwriter.writerow(line)

Value error: could not convert str to float PYTHON

Here is my code. I don't get why I get this error and how to correct it.
The error appears at: totals = entrant + float(tot)
here is my full code:
def total():
File = open("argent.txt","r")
File = File.read()
tot = File
print("You have",tot,"£ in your account")
def add():
entrant = float(input("How many do you want to add to your account? "))
with open("argent.txt", 'r') as f:
tot = f.read().rstrip('\n')
print("You have ",tot,"£ in your account")
totals = entrant + float(tot)
print(totals)
with open("argent.txt", 'w') as f:
output = str(totals)
f.write(output)
add()
Thanks in advance.
In your case the function read() read not only characters 20 but also a new line character(s) appended to it.
So the variable tot contains the value which is not convertible to a number.
Try
tot = tot.strip()
before using it.
In the future, try avoid using File for file type variables.
entrant = float(input("How many do you want to add to your account? "))
with open("argent.txt", 'r') as f:
tot = f.read().rstrip('\n')
print("You have ",tot,"£ in your account")
totals = entrant + float(tot)
print(totals)
with open("argent.txt", 'w') as f:
output = str(totals)
f.write(output)
By using with open the file is close after the following code.
Edit: Fixed the 'w' to file output from float to str

Categories

Resources