So I'm learning python3 at the moment through university - entirely new to it (not really a strong point of mine haha), and i'm not quite sure what i'm missing - even after going through my course content
So the program in question is a text based Stock Management program
and part of the brief is that i be able to search for a line in the text file and print the line on the program
def lookupstock():
StockFile = open('file.txt', 'r')
flag = 0
index = 0
search = str(input("Please enter in the Item: "))
for line in StockFile:
index += 1
if search in line:
flag = 1
break
if flag == 0:
print(search, "Not Found")
else:
print(search)
StockFile.close()
However the output is only what i have typed in if it exists rather than the whole line itself so lets say the line i want to print is 'Kit-Kat, 2003, 24.95' and i search for Kit-Kat
Since the line exists - the output is only
Kit-Kat
Rather than the whole line
Where have I gone wrong? Was I far off?
Greatly appreciated, thank you!
Something like this
if flag == 0:
print(search, "Not Found")
else:
print(search, 'find in line N° ', index , ' line:',line )
StockFile.close()
Alternatively you could open your file using a context manager. This will automatically handle closing the file, here's an example:
def lookupstock():
flag = False
with open('file.txt', 'r') as StockFile:
search = str(input("Please enter in the Item: "))
for index, line in enumerate(StockFile):
if search in line:
print(line, f"Found at line {index}")
flag = True
if not flag:
print(search, "Not Found")
lookupstock()
Results:
Please enter in the Item: test
test Not Found
Please enter in the Item: hello
hello Found at line 0
Setting flags, breaking the loop then testing the flag is not good practice - it's unnecessarily complex. Try this instead:
def LookupStock():
search = input('Enter search item: ')
with open('file.txt') as StockFile:
for line in StockFile:
if search in line:
print(line)
break
else:
print(search, ' not found')
Related
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.
#
# Obtain user input for file name, and open it
#
inFile = open(input("Enter file name: "), "r")
#
# Process data and address possible errors
#
countDinner = 0
countLodging = 0
countConference = 0
valueDinner = 0
valueLodging = 0
valueConference = 0
done = False
while not done :
line = inFile.readline()
try :
s = line
serviceAmount = ';'.join(s.split(';')[1:-1]) #Removes date and name regardless of format
serviceAmount.split(";")
s.lower()
if "dinner" in s :
countDinner = countDinner + 1
valueDinner = valueDinner + int(filter(str.isdigit, s))
print("Dinners: ", countDinner, "Value of Dinner sales: ", valueDinner)
elif "lodging" in s :
countLodging = countLodging + 1
valueLodging = valueLodging + int(filter(str.isdigit, s))
print("Lodging: ", countLodging, "Value of Lodging sales: ", valueLodging)
elif "conference" in s :
countConference = countConference + 1
valueConference = valueConference + int(filter(str.isdigit, s))
print("Conferences: ", countConference, "Value of Conference sales: ", valueConference)
elif line == "" :
done = True
else :
print("Invalid file format.")
except FileNotFoundError :
print("Unable to find file.")
finally :
done = True
inFile.close()
Returns "Invalid file format" even when the document is set up specifically for this code. I'm not getting a syntax error, so I'm not sure whats wrong.
The document contains the text:
John;Lodging;123;050617
Tyler;Conference;123;081497
Taylor;Dinner;453;041798
There are a lot of things you aren't doing quite right here. I tried to not only fix the issue you posted about, but also write some code that should be more clear and easier to use. I left comments to explain things.
# Don't open the file here, just get the file name. We will open in later
fname = input("Enter file name: ")
# I think using dicts is more clearn and organized. Having so many variables I think makes the code messy
counts = {"Dinner": 0,
"Lodging": 0,
"Conference": 0}
values = {"Dinner": 0,
"Lodging": 0,
"Conference": 0}
# Lets try to open the file
try:
with open(fname, 'r') as inFile: # Use "with", this way the file is closed automatically when we are done reading it
for linenum, line in enumerate(inFile): # I want to enumerate each line. If there is an error on a line, we can display the line nmber this way
line = line.lower().split(';')[1:-1] # lets make it all lower case, then split and drop as needed
print(line)
if "dinner" in line :
counts["Dinner"] += 1 # x += 1 is the same as x = x + 1, but cleaner
values["Dinner"] += int(line[1])
print("Dinners: {} Value of Dinner sales: {}".format(counts["Dinner"], values["Dinner"]))
elif "lodging" in line :
counts["Lodging"] += 1
values["Lodging"] += int(line[1])
print("Lodging: {} Value of Dinner sales: {}".format(counts["Lodging"], values["Lodging"]))
elif "conference" in line :
counts["Conference"] += 1
values["Conference"] += int(line[1])
print("Conference: {} Value of Dinner sales: {}".format(counts["Conference"], values["Conference"]))
else :
print("Invalid file format on line {}".format(linenum)) # Here is why we used enumerate in the for loop
except FileNotFoundError:
print("Unable to find file.")
Here is your problem:
serviceAmount = ';'.join(s.split(';')[1:-1]) #Removes date and name regardless of format
serviceAmount.split(";")
You should do:
serviceAmount = ';'.join(s.lower().split(';')[1:-1])
You are checking against lower case strings, but not actually lower casing your input.
It is also important to note that s.lower() doesn't actually change s, it just returns a string where all the letters of s have been switched to lower case. Same thing for split (as in not changing the string its called on, not that it returns a string).
Another problem you are going to run into is getting the numbers from your strings.
int(filter(str.isdigit, s))
Won't work. You can use split again like you did earlier (or just not re-join since you only care about the first element in the comparisons).
int(serviceAmount.split(';')[1])
The last thing is the
finally:
done = True
inFile.close()
finally always runs when exiting a try, meaning that you are always done after each loop (and close the file after you read the first line).
If you remove the finally and add inFile.close() inside the elif line == "" it will close, and set done only when you've reached the end of the file.
It could be done as simple as
categories = {}
filename = input("Enter file name: ")
with open(filename, "r") as file:
name, category, value, date = file.readline().split(";")
if category not in categories:
categories[category] = {"count": 0, "value": 0}
categories[category]["count"] += 1
categories[category]["value"] += int(value)
At the end, you'll have a dict with categories, their count, and value, and also their names are not hard-coded.
I have this code:
b = str(raw_input('please enter a book '))
searchfile = open("txt.txt", "r")
for line in searchfile:
if b in line:
print line
break
else:
print 'Please try again'
This works for what I want to do, but I was wanting to improve on it by repeating the loop if it goes to the else statement. I have tried running it through a while loop but then it says 'line' is not defined, any help would be appreciated.
Assuming you want to repeat the search continually until something is found, you can just enclose the search in a while loop guarded by a flag variable:
with open("txt.txt") as searchfile:
found = False
while not found:
b=str(raw_input('please enter a book '))
if b == '':
break # allow the search-loop to quit on no input
for line in searchfile:
if b in line:
print line
found = True
break
else:
print 'Please try again'
searchfile.seek(0) # reset file to the beginning for next search
Try this:
searchfile = open("txt.txt", "r")
content = searchfile.readlines()
found = False
while not found:
b = raw_input('Please enter a book ')
for line in content:
if b in line:
print line
found = True
break
else:
print 'Please try again'
searchfile.close()
You load the content in a list and use a boolean flag to control if you already found the book in the file. When you find it, you're done and can close the file.
i have the next code:
bestand = open("6_frame.txt", "r")
seq = bestand.readlines()
#to make a list
for line in seq:
alle = line
while True:
if alle.isupper():
break
else:
print ("try again ")
with this code i want to make sure that someone , who write a sequence in the file, write this sequence in capital letters, and want to except the other errors: but he want do what i want.
can somebody help me ??
I think you are saying you want to ensure the entire file is in upper-case. If that's what you are looking for, this will do the trick:
if all(x.isupper() for x in open("6_frame.txt", "r")):
print("entire file is upper-case.")
else:
print("try again!")
This will test the file, line-at-a-time, for all upper-case characters. If it finds a line that is not, it will return false, otherwise if all lines are upper-case, return true (and print "entire file is upper-case").
Update (File watching edition)
It looks like you want to keep checking the file until it's all uppercase. Here's a fairly ineffecient way to do it (you could add modtime checks, or use inotify to make it better):
from time import sleep
while True:
lines = open("6_frame.txt", "r")
if all((x.isupper() or x.isspace()) for x in lines):
print("entire file is upper-case.")
break # We're done watching file, exit loop
else:
print("try again!")
sleep(1) # Wait for user to correct file
Also, you may get exceptions (I'm not sure) if the person is mid-save when your script checks the file again, so you may need to add some exception catching around the all line. Either way... Hope this helps!
My abc.txt content is aBC, so not all uppercase:
fd = open('abc.txt','r')
seq = fd.readlines()
for line in seq:
if line.isupper():
print('all capital')
else:
print('try again')
therefore my output = try again
if my abc.txt content is ABC my output is all capital
Determine whether all cased characters in the file are uppercase, retry if not:
import time
from hashlib import md5
hprev = None
while True:
with open("6_frame.txt") as f:
text = f.read()
if text.isupper():
print('all capital')
break
else:
h = md5(text).hexdigest()
if h != hprev: # print message if the file changed
print('try again')
hprev = h
time.sleep(1) # wait for the file to change