everyone. I have a Python assignment that requires me to do the following:
Download this CSV fileLinks to an external site of female Oscar winners (https://docs.google.com/document/d/1Bq2T4m7FhWVXEJlD_UGti0zrIaoRCxDfRBVPOZq89bI/edit?usp=sharing) and open it into a text editor on your computer
Add a text file to your sandbox project named OscarWinnersFemales.txt
Copy and paste several lines from the original file into your sandbox file. Make sure that you include the header.
Write a Python program that does the following:
Open the file and store the file object in a variable
Read the entire contents line by line into a list and strip away the newline character at the end of each line
Using list slicing, print lines 4 through 7 of your file
Write code that will ask the user for an actress name and then search the list to see if it is in there. If it is it will display the record and if it is not it will display Sorry not found.
Close the file
Below is the code I currently have. I've already completed the first three bullet points but I can't figure out how to implement a search function into the list. Could anyone help clarify it for me? Thanks.
f = open('OscarsWinnersFemales.txt')
f = ([x.strip("\n") for x in f.readlines()])
print(f[3:7])
Here's what I tried already but it just keeps returning failure:
def search_func():
actress = input("Enter an actress name: ")
for x in f:
if actress in f:
print("success")
else:
print("failure")
search_func()
I hate it when people use complicated commands like ([x.strip("\n") for x in f.readlines()]) so ill just use multiple lines but you can do what you like.
f = open("OscarWinnersFemales.txt")
f = f.readlines()
f.close()
data = {} # will list the actors and the data as their values
for i, d in enumerate(data):
f[i] = d.strip("\n")
try:
index, year, age, name, movie = d.split(",")
except ValueError:
index, year, age, name, movie, movie2 = d.split(",")
movie += " and " + movie2
data[name] = f"{index}-> {year}-{age} | {movie}"
print(f[3:7])
def search_actr(name):
if name in data: print(data[name])
else: print("Actress does not exist in database. Remember to use captols and their full name")
I apologize if there are any errors, I decided not to download the file but everything I wrote is based off my knowledge and testing.
I have figured it out
file = open("OscarWinnersFemales.txt","r")
OscarWinnersFemales_List = []
for line in file:
stripped_line = line.strip()
OscarWinnersFemales_List.append(stripped_line)
file.close()
print(OscarWinnersFemales_List[3:7])
print()
actress_line = 0
name = input("Enter An Actress's Name: ")
for line in OscarWinnersFemales_List:
if name in line:
actress_line = line
break
if actress_line == 0:
print("Sorry, not found.")
else:
print()
print(actress_line)
So im making a name generator/finder, So for the find command i want to find that name in the txt file with the line number! So how do i find the name with the line number?
line = 0
names = open(r"names.txt", "r")
name1 = names.readlines()
uname = input("Please enter the name you want to find: ")
for name in name1:
try:
print(name)
print(line)
if name == uname:
print(f"Found name: {name} \nLine No. {line + 1}")
else:
line = line + 1
except:
print("Unable to process")
But it seems to not work except if you write the last name in file it works. So could give any help?
EDIT: Ive found a way so you can reply if you want to for further people running into the problem!
Try this:
with open("names.txt", "r") as f:
file_contents = names.read().splitlines()
uname = input("Please enter the name you want to find: ")
for line, row in enumerate(file_contents):
if uname in row:
print('Name "{0}" found in line {1}'.format(uname, line))
Yo
if "namefilled" in name :
print("found it")
You can use pathlib if you have Python 3.4+. Pretty handy library.
Also, context management is useful.
# Using pathlib
from pathlib import Path
# https://docs.python.org/3/library/fnmatch.html?highlight=fnmatch#module-fnmatch
import fnmatch
# Create Path() instance with path to text file (can be reference)
txt_file = Path(r"names.txt")
# Gather input
uname = input("Please enter the name you want to find: ")
# Set initial line variable
line = 0
find_all = False
# Use context maangement to auto-close file once complete.
with txt_file.open() as f:
for line in f.readlines():
# If python 3.8, you can use assignment operator (:=)
if match_list := fnmatch.filter(line, uname) is not None: # Doe not match substring.
number_of_names = len(match_list)
name_index = [i for i, element in enumerate(line.split()) for word in match_list if word == element]
print(f"""
{number_of_names} name{"s" if number_of_names > 0 else ""} found on line {line} at position {name_index}.
""".strip())
line += 1
Edited to include fnmatch per some other comments in this thread about matching the full string vs. a substring.
You could try something like this:
import re
search_name = input("Enter the name to find: ")
with open("names.txt", "r") as f:
for line, row in enumerate(f.read().splitlines()):
if re.findall('\\b'+search_name+'\\b', row, flags=re.IGNORECASE):
print('Name "{0}" found in line {1}'.format(search_name, line))
You can remove the flags=re.IGNORECASE flag in case you want the seaarch to be case-sensetive.
I am new to python and am looking for guidance on the task I am working on.
I am importing a csv file that looks like the list below.
invoice_id,customer_first_name,customer_last_name,part_number,quantity,total
18031,Hank,Scorpio,367,1,2.63
54886,Max,Power,171,3,50.79
19714,Jonathan,Frink,179,2,7.93
19714,Jonathan,Frink,378,2,32.34
22268,Gil,Gunderson,165,2,47.15
87681,Lionel,Hutz,218,1,50.83
84508,Lurleen,Lumpkin,257,1,81.95
34018,Lionel,Hutz,112,3,88.88
34018,Lionel,Hutz,386,3,86.04
34018,Lionel,Hutz,216,1,53.54
66648,Patty,Bouvier,203,3,70.47
I only want to print each line if its based off the criteria inputted by the user. For example, if the user inputs lname and then inputs Hutz the following would be printed out.
87681,Lionel,Hutz,218,1,50.83
34018,Lionel,Hutz,112,3,88.88
34018,Lionel,Hutz,386,3,86.04
34018,Lionel,Hutz,216,1,53.54
4 records found.
This is what I have so far...
salesdatafile= None
while True:
salesdatafilename=input("Enter the name of the file:")
try:
salesdata= open(salesdatafilename, 'r')
break
except FileNotFoundError:
print("{0} was not found".format ( salesdatafilename ))
search=input("Do you want to search by invoice id or lname? Please type id or lname: ")
idsearch=salesdata.readline()
if search== 'id':
idnumber=print(int(input('Please enter Id to search: ')))
while idsearch != '':
if idsearch== idnumber:
print(idsearch)
else:
lname=print(input('Please enter your last name: '))
while idsearch != '':
if idsearch== lname:
print(idsearch)
All that is printing out is lname or id inputted by the user.
Python has a csv module built in that you should be utilizing. Check out the below example code:
import csv
salesdatafilename = r"path/to/file.txt"
data = csv.reader(open(salesdatafilename))
last_name_to_look_for = "Lionel"
for invoice_id, customer_first_name, customer_last_name, part_number, quantity, total in data:
if customer_last_name == last_name_to_look_for:
print(invoice_id, customer_first_name, customer_last_name, part_number, quantity, total)
In your code you are comparing the entire line to the idnumber or lname. Instead you might want to try something like
if lname in idsearch:
<do something>
this will check if the lname is in the line somewhere.
For performance, I will use a generator to read the lines so that my program doesn’t crash were this to be a bigger file. So I will yield each line in that file with a generator function. Since generators return iteratirs, I will then iterate and filter every line that does not contain my search value and return only those that contain my search value.
I created this script that could be used as a login, and then created an external text file that has the data 1234 in it, this is attempting to compare the data from the file, but outputs that the two values are different, even though they are the same. Thanks In advance to any help you can give me, the code I used is below:
getUsrName = input("Enter username: ")
file = open("documents/pytho/login/cdat.txt", "r")
lines = file.readlines()
recievedUsrName = lines[1]
file.close()
print(getUsrName)
print(recievedUsrName)
if recievedUsrName == getUsrName:
print("hello")
elif getUsrName != recievedUsrName:
print("bye")
else:
Try it like:
if recievedUsrName.strip() == getUsrName:
...
It must be the trailing newline.
`File = input("Please enter the name for your txt. file: ")
fileName = (File + ".txt")
WRITE = "w"
APPEND = "a"
file = []
name = " "
while name != "DONE" :
name = input("Please enter the guest name (Enter DONE if there is no more names) : ").upper()
fileName.append(name)
fileName.remove("DONE")
print("The guests list in alphabetical order, and it will save in " + fileName + " :")
file.sort()
for U in file :
print(U)
file = open(fileName, mode = WRITE)
file.write(name)
file.close()
print("file written successfully.")
`
I am just practicing to write the file in Python, but something bad happened. Please help me. Thank you.
The code.
The error description.
Here are still some errors about this :
fileName.remove("DONE")
Still showing 'str' error.
THANK YOU
You try to append to string which is not correct in Python, instead try:
filename += 'name'
You're trying to build a list of names. Start with a list:
guests = []
and then append the values provided by your user:
while name is not "Done":
prompt = "Please input the name of the next guest, or 'Done'."
guests.append(input(prompt).upper())
then you can sort that list and write the values to the file. (which you seem to have a handle on)
Appending the guests' names to fileName, or concatenating them onto it, wouldn't make a lot of sense. You'd end up with something like "data.txtJOEBOBJANELINDA" which would do you no good at all.