How to append data to CSV file using pandas and User Input? - python-3.x

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

Related

I need some help understanding what is happening here?

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

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 to create a loop in a user interactive script which can add any number of tags in image series?

I want to loop over dicom tags and image series in my script in a user interactive way.
But I am unable to create a loop, which can ask user:
Do you want to modify or add tags?
if add then
How many tags you want to add?
and if no
then which tags you want to modify?
and then ask for the tags details and then later add them into my image series..
I have written a user interactive script which i will share with you, which can ask user to add any two tags in any image series(MRI, PET or CT).
tag1 = input("Enter the tag: ")
VR1 = input("Enter VR: ")
Value1 = input("Enter the value at VR: ")
tag2 = input("Enter the tag: ")
VR2 = input("Enter VR: ")
Value2 = input("Enter the value at VR: ")
for imagePath in image_path_list:
image = dcmread(imagePath)
image.add_new(tag1, VR1, Value1)
image.add_new(tag2, VR2, Value2)
image.add_new(0x00180020, 'CS', 'GR')
image.add_new(0x00180021, 'CS', 'SP\OSP')
src_fname, ext = os.path.splitext(imagePath)
'''
I expect a loop over my tags and image series in a interactive way.
The code below will ask for a number of tags and values to enter. This assumes the tags are all in the DICOM dictionary, in which case you do not need the VR; pydicom will look it up. With the latest code in the pydicom repository, the 'tag' can also be the DICOM keyword, e.g. 'PatientName', 'PatientID'.
As per usual pydicom assignment, the code will modify the data element if it already exists; otherwise it will be added.
All datasets are changed in the same way. If that is not what you wanted, you could loop first over the datasets, and enter tags and values only for that dataset.
from pydicom import dcmread
from pydicom.tag import Tag
import glob
image_path_list = glob.glob(r"c:\temp\dicom\*.dcm")
datasets = [dcmread(filepath) for filepath in image_path_list]
print("\n\nEnter tag=value, one per line. When done, enter blank and datasets will be written)")
while True:
pair = input("Enter in form tag=value...:")
if pair == "":
break
if "=" not in pair:
print("Entry must contain an = sign")
print()
continue
# Parse line, stripping away extra spaces
tag, value = [x.strip() for x in pair.split("=")]
try:
tag = Tag(tag)
except:
print("Tag not in a valid format")
print()
continue
for ds in datasets:
ds[tag].value = value
# Write all the modifications:
for ds in datasets:
ds.save_as(ds.filename)
Example use:
Enter in form tag=value...:0x100010=Lastname^Firstname
Enter in form tag=value...:0x100020=id123
Enter in form tag=value...:SliceLocation=23.5
Enter in form tag=value...:

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