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.
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)
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'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)
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