I need some help understanding what is happening here? - python-3.x

Screenshot of the CSV file I am inputting
This is my code that I am trying to run. I am trying to make call functions to make the program run. get_toc_tuple is supposed to split the lines in columns. read_toc is supposed to read the file and copy the columns to a list. get_cell is one of the options you would be able to do. Eventually I want to be able to get_work_phone and get_shift. print_cell is supposed to print the correct info for name and cell phone number.
I can't figure out why these call functions are not working.
It is only printing:
Team Member Cell Phone
My Code:
import re
def get_toc_tuple(line_str):
data = re.split(r'\s{2,}', line_str)
team_member = data[0]
desk_phone = data[2]
cell_phone = data[3]
shift = data[4]
return (team_member, desk_phone, cell_phone, shift)
def read_toc(filename):
fileread = open(filename, 'r')
toc_list = []
fileread.readlines()[0]
for line in fileread.readlines()[1:]:
toc_list.append(get_toc_tuple(line.strip()))
fileread.close()
return toc_list
def get_cell(toc_list):
cell_list = []
for tup in toc_list:
if name in tup[0]:
cell_list.append(tup[3])
return cell_list
def print_cell(cell_list):
print('%-19s%-1s%-13s\n' % ('Team Name', ' ', 'Cell Phone'))
for line in cell_list:
team_member = line[0]
cell_phone = line[3]
print('%-19s%-1s%-13s\n' % (team_member, ' ', cell_phone))
if __name__ == '__main__':
option = input("Cell Phone, Work Phone, or Shift? ")
name = input('Employee: ')
filename = input('Select a file location: ')
toc_list = read_toc(filename)
if option == 'Cell Phone':
cell_list = get_cell(toc_list)
print_cell(cell_list)
[1]: https://i.stack.imgur.com/ZrblW.png

These kind of problems are easiest to solve using the csv module. Try to export your file in csv format (using excel or any other tool):
Team Member,Title,Desk Phone,Cell Phone,Shift
Bob Smith,Technical Support,xxx-xxx-xxxx,xxx-xxx-xxx,M-F 8a-5p
Todd Wilson,Technical Support,616-233-5065,734-709-1472,M-F 8a-5p
Then use:
import csv
rows = []
file = open("D:/team.csv")
with file:
read = csv.DictReader(file)
for row in read:
rows.append(dict(row))
After above code is executed, rows list will contain the rows in the file mapped on the header row items:
[{'Team Member': 'Bob Smith', 'Title': 'Technical Support', 'Desk Phone': 'xxx-xxx-xxxx', 'Cell Phone': 'xxx-xxx-xxx', 'Shift': 'M-F 8a-5p'}, {'Team Member': 'Todd Wilson', 'Title': 'Technical Support', 'Desk Phone': '616-233-5065', 'Cell Phone': '734-709-1472', 'Shift': 'M-F 8a-5p'}]
Once you have this list is very easy to parse it and extract any info you want. For example Desk phone and Shift for Team Member Todd Wilson, will be something like:
for row in rows:
if row['Team Member'] == 'Todd Wilson':
print(row['Desk Phone'], row['Shift'])

Related

CSV manipulation problem. A little complex and would like the solution to not be using pandas

CSV file:
Acct,phn_1,phn_2,phn_3,Name,Consent,zipcode
1234,45678,78906,,abc,NCN,10010
3456,48678,,78976,def,NNC,10010
Problem:
Based on consent value which is for each of the phones (in 1st row: 1st N is phn_1, C for phn_2 and so on) I need to retain only that phn column and move the remaining columns to the end of the file.
The below is what I have. My approach isn't that great is what I feel. I'm trying to get the id of the individual Ns and Cs, get the id and map it with the phone (but I'm unable to iterate through the phn headers and compare the id's of the Ns and Cs)
with open('file.csv', 'rU') as infile:
reader = csv.DictReader(infile) data = {} for row in reader:
for header, value in row.items():
data.setdefault(header, list()).append(value) # print(data)
Consent = data['Consent']
for i in range(len(Consent)):
# print(list(Consent[i]))
for idx, val in enumerate(list(Consent[i])):
# print(idx, val)
if val == 'C':
#print("C")
print(idx)
else:
print("N")
Could someone provide me with the solution for this?
Please Note: Do not want the solution to be by using pandas.
You’ll find my answer in the comments of the code below.
import csv
def parse_csv(file_name):
""" """
# Prepare the output. Note that all rows of a CSV file must have the same structure.
# So it is actually not possible to put the phone numbers with no consent at the end
# of the file, but what you can do is to put them at the end of the row.
# To ensure that the structure is the same on all rows, you need to put all phone numbers
# at the end of the row. That means the phone number with consent is duplicated, and that
# is not very efficient.
# I chose to put the result in a string, but you can use other types.
output = "Acct,phn,Name,Consent,zipcode,phn_1,phn_2,phn_3\n"
with open(file_name, "r") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
# Search the letter “C” in “Consent” and get the position of the first match.
# Add one to the result because the “phn_×” keys are 1-based and not 0-based.
first_c_pos = row["Consent"].find("C") + 1
# If there is no “C”, then the “phn” key is empty.
if first_c_pos == 0:
row["phn"] = ""
# If there is at least one “C”, create a key string that will take the values
# phn_1, phn_2 or phn_3.
else:
key = f"phn_{first_c_pos}"
row["phn"] = row[key]
# Add the current row to the result string.
output += ",".join([
row["Acct"], row["phn"], row["Name"], row["Consent"],
row["zipcode"], row["phn_1"], row["phn_2"], row["phn_3"]
])
output += "\n"
# Return the string.
return(output)
if __name__ == "__main__":
output = parse_csv("file.csv")
print(output)

How to append data to CSV file using pandas and User Input?

I've posted about this before using import csv and couldn't figure it out, but now I've decided to step it "up a notch" and use pandas instead. When I try to add data using User Input, I cannot figure out why it won't update. I attempted to look up some solutions online but can't find any. I will add my code and then a photo of what the CSV file looks like and another photo of what the actual program looks like when information is entered into the command line . What I'm trying to accomplish is have a new Name, Location, and Email added at the end of the data(CSV file) and then saved. But nothing happens when it is entered.
import pandas as pd
dataset = pd.read_csv(r'C:\Users\benji\OneDrive\Desktop\My Coding Work\.vscode\.vscode\CSVFiles\emails_demo.csv')
names = list(dataset.Name)
locations = list(dataset.Location)
emails = list(dataset.Email)
def get_email_by_loc(location):
correct_emails = list(dataset.loc[dataset.Location == location].Email)
return correct_emails
def add_data():
global names
global locations
global emails
global dataset
add_name = input('Enter Name: ')
add_location = input('Enter Location: ')
add_email = input('Enter Email: ')
names.append(add_name)
locations.append(add_location)
emails.append(add_email)
while True:
start_search = input('What would you like to search?(Name/Location/Email/Add Data): ')
if start_search == 'Location' or start_search == 'location':
location_search = input('Enter Location: ')
for emails in get_email_by_loc(location_search):
print(emails)
if start_search == 'Add Data' or start_search == 'add data':
add_data()
CSV: https://imgur.com/a/ziESanM
Command Line: https://imgur.com/a/UDRoiDj
names = list(dataset.Name)
locations = list(dataset.Location)
emails = list(dataset.Email)
returns list that are not associated with the original dataframe (ie you are appending to arrays that are not even associated with the original dataframe) so when you are going to rewrite to the csv file, you are not appending to the original dataframe. I would recommend fixing the add_data function to append to the end of the dataframe.
One quick (but no where close to ideal) version to do so would be
def add_data():
global dataset
add_name = input('Enter Name: ')
add_location = input('Enter Location: ')
add_email = input('Enter Email: ')
dataset.loc[len(dataset)]=[add_name,add_location,add_email ]
If you would like to write to the original csv file, you may use dataset.to_csv(file_path)
This is more ideal, let me know if it works

How to print values according to same lines from two different text files

I wanted the user to input a particular product name (which is saved in a file) and accordingly I wanted to print out price of the product (saved in a different file), but not able to do so.
I have just started out programming, so it's new to me.
def find_in_file(f) :
myfile = open("file1.txt")
products = myfile.read()
products = products.splitlines()
if f in products:
return "Product is in list"
else:
return "Product is not in list"
def printing_in_file(p) :
myprice = open("file2.txt")
price = myprice.read()
price = price.splitlines()
return price
if code in sec_code.values():
product = input("Enter product name: ")
print(printing_in_file(p))
I expected the price to be the output, but I am getting name 'p' is not defined.
This answer below works, but it is not complete, because you did not provide samples of your input files.
The code that you provided does not have a 'p' variable, so I replace it with the variable product. I created bool values for the returns in the function find_product (which was named find_in_file). If the inputted product name is an exact match (this will create problems) then a bool value of True is return. Next the code will call the function find_product_price (which was named printing_in_file) for the product name. I had to create files containing product names and prices, because you did not provide sample files as part of your question.
This code works, but it has limitation, because I do not know the exact format of your inputs files or sec_code values. With additional information this code can be improved or something new might replace some of it with something better.
Good luck with this coding problem.
def find_product(product_name) :
inventory_file = open('tmpFile.txt', 'r', encoding='utf-8')
products = inventory_file.read()
products = products.splitlines()
if product_name in products:
return True
else:
return False
def find_product_price(product_name) :
product_prices = open('tmpFile01.txt', 'r', encoding='utf-8')
prices = product_prices.read()
price = prices.splitlines()
if product_name in price:
return price
product = input("Enter product name: ")
product_search = find_product(product)
if product_search == True:
print ('The product is available.')
print(find_product_price(product))
# outputs
['cisco router $350']
elif product_search == False:
print (f'{product} are not available for purchase.')

How can I print the required row when reading a csv file in python

I am a beginner of python, I have an assignment that wants me to read a csv file and print out the related information.
I have an excel file which includes student's ID, school and hobby.
now I want to write a program to show the detail of the student by entering the ID.
requirements are:
print the entire row when ID is correctly input
print "Empty, try again" when ID input is space
print "No record" when the input is invalid or there is no matching record
I manage to fulfill the first 2 requirements but have no idea how to get the third. Seems like my code is always looping through each of the data and print "No record" every time, i.e. if there are 3 records, 3 "No record" will be printed. Could someone help me with it? Much thanks! Below will be my code.
import csv
file = "a.csv"
sID = input("Enter ID: ")
while (sID == " "):
print("Empty input,enter again")
sID = input("Enter ID: ")
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if (sID == row["id"]):
print("{0}{1}{2}".format(row[id],row[school],row[hobby])
else:
print("No record")
You need a few changes:
You should use the str.strip() method to test if a string is empty so that it accounts for any number of spaces.
You should quote the column names to make them string literals when using them as indices to access the value of a column in the current row.
You should use the optional else block for your for loop to determine that there is no matching record found, and break the loop if there is one found.
You are missing a right parenthesis for the print call that outputs a row.
With the above changes, your code should look like:
import csv
file = "a.csv"
sID = input("Enter ID: ")
while not sID.strip():
print("Empty input,enter again")
sID = input("Enter ID: ")
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if (sID == row["id"]):
print("{0}{1}{2}".format(row['id'],row['school'],row['hobby']))
break
else:
print("No record")

Using and input string to find a tuple in a text file

This is my code so far. I have tried to get an input from the user to search for a tuple of 3 parts in my source code. But I can not figure out how to allow the user to find the code through input and give them the tuple. If the the name variable is changed to 'Fred' it is found with ease but the code needs for the users input. All help is much appreciated.
def details():
countries = []
file = open('file.txt', mode='r', encoding='utf-8')
file.readline()
for line in file:
parts = line.strip().split(',')
country = Country(parts[0], parts[1], parts[2])
countries.append(country)
file.close()
with open('file.txt', encoding='utf=8') as countries:
for country in countries:
name=str(input('enter:'))
if str(name) in country:
print(country)

Resources