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.
Related
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')
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.
Text file:
1. line
2. line
3. line
4. line
...
code:
quit = False
while not quit:
with open("sample.txt", "r+") as file:
n = len(file.read().split("\n"))
idea = input(f"Enter idea no. {n}: ")
if idea == "--q":
quit = True
elif idea == "--list":
with open("sample.txt", "r") as file:
print(f"\n{file.read()}\n")
elif idea == f"--del {type(int)}": #if user enter i.e. '--del 4' it dels line 4
with open("sample.txt", "r") as file:
l = idea.split(" ")[1]
lines = file.readlines()
del lines[l]
del_idea = open("sample.txt", "w")
for line in lines:
del_idea.write(line)
del_idea.close()
else:
file.write(f"{n}. {idea}\n")
How to implement delete a line selected by user?
problematic line: elif idea == f"--del {type(int)}"
User wants to delete chosen line using syntax i.e --del 4, command must be in one single line. If a digit is not given after blank " " (space) in input, should loop until enters it properly.
Any ideas? Should use regex ?
Your problem is that f-strings don't work like regex. type(int) is the actual type class so you're basically checking if the user literally input "--del <class 'type'>" (which is never the case I believe).
You can use regex to match a pattern of del followed by a number (i.e, r"--del \d+"), but an easier way would be to split the input and access the arg and number easily:
quit = False
while not quit:
with open("sample.txt", "r+") as file:
n = len(file.read().split("\n"))
idea = input(f"Enter idea no. {n}: ").split()
if idea[0] == "--q":
quit = True
elif idea[0] == "--list":
...
elif idea[0] == "--del":
with open("sample.txt", "r") as file:
l = idea[1]
...
else:
file.write(f"{n}. {idea}\n")
I am stuck why the words.txt is not showing the full grid, below is the tasks i must carry out:
write code to prompt the user for a filename, and attempt to open the file whose name is supplied. If the file cannot be opened the user should be asked to supply another filename; this should continue until a file has been successfully opened.
The file will contain on each line a row from the words grid. Write code to read, in turn, each line of the file, remove the newline character and append the resulting string to a list of strings.After the input is complete the grid should be displayed on the screen.
Below is the code i have carried out so far, any help would be appreciated:
file = input("Enter a filename: ")
try:
a = open(file)
with open(file) as a:
x = [line.strip() for line in a]
print (a)
except IOError as e:
print ("File Does Not Exist")
Note: Always avoid using variable names like file, list as they are built in python types
while True:
filename = raw_input(' filename: ')
try:
lines = [line.strip() for line in open(filename)]
print lines
break
except IOError as e:
print 'No file found'
continue
The below implementation should work:
# loop
while(True):
# don't use name 'file', it's a data type
the_file = raw_input("Enter a filename: ")
try:
with open(the_file) as a:
x = [line.strip() for line in a]
# I think you meant to print x, not a
print(x)
break
except IOError as e:
print("File Does Not Exist")
You need a while loop?
while True:
file = input("Enter a filename: ")
try:
a = open(file)
with open(file) as a:
x = [line.strip() for line in a]
print (a)
break
except IOError:
pass
This will keep asking untill a valid file is provided.
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