Print Statement executing twice Python - python

When a user enters an input and if it is not available, the print executes twice
How do I fix it???
if ask.lower() == 'open':
with open(filename, 'r') as f:
contents = f.read().splitlines()
search_name = input("What is your name? ")
for line in contents:
if line.find(search_name) != -1:
print(line)
else:
print("Unable to find your name")
output:
Unable to find your name
Unable to find your name

Here is a more robust construct:
if ask.lower() == 'open':
with open(filename) as f:
name = input('What is your name? ')
for line in f:
if name in line:
print(line)
break
else:
print('Unable to find your name')

You are invoking the print command for every entry in your file!
Let me clarify, for the name that you get as input into search_name, you are looping over EVERY LINE that you have read from a file (in your case it seems that the file had 2 lines).
Your if cluase is not what you want. What you need is something like this:
if ask.lower() == 'open':
with open(filename, 'r') as f:
contents = f.read().splitlines()
search_name = input("What is your name? ")
is_found = false
for line in contents:
if line.find(search_name) != -1:
is_found = true
print(line)
if not is_found:
print("Unable to find your name")

Related

How to delete a line of text in python (minimal reproducable example)

The code I have used to delete a line from a file is deleting everything in the text file instead of the line that includes the name I input. Is there a fix for this, if so please could it be demonstrated?
def playerMenu():
runningplayer = True
while runningplayer == True:
time.sleep(0.3)
print("\n====================================================")
print("************Welcome to The Player Menu**************")
print("====================================================")
time.sleep(0.2)
choice = input('''
========================================================
A: Add Player & Score
B: Delete Player
C: View Scores
D: Back To Main Menu
E: Exit Menu
========================================================
\nPlease select what you wish to do: ''')
#This ELIF statement will allow the user to write the name and score of the player.
if choice == "A" or choice == "a":
save_name = input('Enter your name. ').title()
save_score = input('Enter your score. ')
text_file = open("highscores.txt", "a")
text_file.write("\n" + save_name + ' | ' + save_score + "\n")
text_file.close()
text_file = open("highscores.txt", "r")
whole_thing = text_file.read()
print (whole_thing)
text_file.close()
#This ELIF statement will allow the user to delete a player from the text file.
elif choice == "B" or choice == "b":
print("These are the current players and their score")
text_file = open("highscores.txt", "r")
whole_thing = text_file.read()
print (whole_thing)
text_file.close()
time.sleep(0.3)
save_delete = input("Please enter the name of the player you wish to delete: ")
with open("highscores.txt", "r") as f:
lines = f.readlines()
with open("highscores.txt", "w") as f:
for line in lines:
if line.strip("\n") != save_delete:
f.write(lines)
print(lines)
I took you Option B section code and modified it a little. Then, I included the delimitating character in the name of the line that needs to be deleted (to ensure that the whole name is being taken into account).
My test text file's contents looked like this:
bert|10\nbertha|9\nsam|8\nben|8\nhayley|6
My test code looks like this:
import time
print("These are the current players and their score")
text_file = open("highscores.txt", "r")
whole_thing = text_file.read()
print(whole_thing)
text_file.close()
time.sleep(0.3)
save_delete = input("Please enter the name of the player you wish to delete: ") + "|"
print(f"save_delete = {save_delete}")
with open("highscores.txt", "r") as f:
lines = f.readlines()
print(lines)
with open("highscores.txt", "w") as f:
for line in lines:
if not(line.startswith(save_delete)):
f.write(line)
If i run this, and choose te delete "bert", it only deletes bert (and not bertha as well). My text file's content results in:
bertha|9\nsam|8\nben|8\nhayley|6

Text in file is not printing

I want to print text from a file but the output doesn't show anything.
def viewstock():
replit.clear()
print ("Here is the current stock\n-------------------------")
f = open("stock", "a+")
p = f.read()
print (p)
print ("Press enter to return to the stock screen")
e = input ('')
if e == '':
stock_screen()
else:
stock_screen()
Anyone know how to fix this?
You can just open the file in read mode, and not append mode. Try this code:
f = open('stock', 'r') -> #(r stands for read mode)
file_contents = f.read()
print (file_contents)
f.close()
To read a file and print, you may want to just open the file in read mode.
def viewstock():
replit.clear()
print ("Here is the current stock\n-------------------------")
with open("stock", "r") as f:
p = f.readlines()
print (p)
print ("Press enter to return to the stock screen")
e = input ('')
stock_screen() #You just need to call it once
#this entire section can be ignored and instead the above line will do
'''
The if and else does the same thing. So no need to use if statement
if e == '':
stock_screen()
else:
stock_screen()
'''
If you want to read from a file open it in read mode and not append mode. When you open it in append mode the file's position is at the end where it returns nothing.
try this:
def viewstock():
replit.clear()
print ("Here is the current stock\n-------------------------")
f = open("stock", "r")
p = f.read()
print (p)
print ("Press enter to return to the stock screen")
e = input ('')
if e == '':
stock_screen()
else:
stock_screen()

How to replace/change element in txt.file

Im trying to replace a cetain element in a txt file.
let say that if i find the name in telephonelist.txt, i want i to change the number to this person with the input value of newNumber.
let's say that name = Jens, then i want it to return 99776612 that is the tlf number to Jens, and then the input of 'newNumber' will replace this number. i am new to python.
def change_number():
while True:
try:
name = input('Name: ') #Enter name
newNumber = input('New number: ') # Wanted new number
datafile = open('telephonelist.txt')
if name in open('telephonelist.txt').read():
for line in datafile:
if line.strip().startswith(name):
line = line.replace(name,newNumber)
print('I found', name)
quit()
else:
print('I could not find',name+',','please try again!\n')
continue
except ValueError:
print('nn')
change_number()
This i telephonelist.txt
Kari 98654321
Liv 99776655
Ola 99112233
Anne 98554455
Jens 99776612
Per 97888776
Else 99455443
Jon 98122134
Dag 99655732
Siv 98787896
Load content, modify it, seek to beginning of the file, write the modified content again and then truncate the rest.
def change_number():
name = input('Name: ') #Enter name
newNumber = input('New number: ') # Wanted new number
with open('telephonelist.txt', 'r+') as file:
data = file.read().splitlines()
data = [line if not line.split()[0] == name else f"{name} {newNumber}" for line in data]
file.seek(0)
file.write("\n".join(data))
file.truncate()
change_number()

Using the split() or find() function in python

Am writing a program that opens a file and looks for line which are like this:
X-DSPAM-Confidence: 0.8475.
I want to use the split and find function to extract these lines and put it in a variable. This is the code I have written:
fname = raw_input("Enter file name: ")
if len(fname) == 0:
fname = 'mbox-short.txt'
fh = open(fname,'r')
total = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:"): continue
Please, Please I am now beginning in python so please give me something simple which I can understand to help me later on. Please, Please.
I think the only wrong part is not in if :
fname = raw_input("Enter file name: ")
if len(fname) == 0:
fname = 'mbox-short.txt'
fh = open(fname,'r')
total = 0
lines = []
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
lines.append(line)
First receive the input with raw_input()
fname = raw_input("Enter file name: ")
Then check if the input string is empty:
if not fname:
fname = 'mbox-short.txt'
Then, open the file and read it line by line:
lines = []
with open(fname, 'r') as f:
for line in f.readlines():
if line.startswith("X-DSPAM-Confidence:"):
lines.append(line)
The with open() as file statement just ensures that the file object gets closed when you don't need it anymore. (file.close() is called automatically upon exiting out of the with clause)
I know where this one is coming from as I've done it myself some time ago. As far as I remember you need to calculate the average :)
fname = raw_input("Enter file name: ")
fh = open(fname)
count = 0
sum = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
count = count + 1
pos = line.find(' ')
sum = sum + float(line[pos:])
average = sum/count
You're very close, you just need to add a statement below the continue adding the line to a list.
fname = raw_input("Enter file name: ")
if len(fname) == 0:
fname = 'mbox-short.txt'
fh = open(fname,'r')
total = 0
lines = []
for line in fh:
if not line.startswith("X-DSPAM-Confidence:"):
continue
lines.append(line) # will only execute if the continue is not executed
fh.close()
You should also look at the with keyword for opening files - it's much safer and easier. You would use it like this (I also swapped the logic of your if - saves you a line and a needless continue):
fname = raw_input("Enter file name: ")
if len(fname) == 0:
fname = 'mbox-short.txt'
total = 0
good_lines = []
with open(fname,'r') as fh:
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
good_lines.append(line)
If you just want the values, you can do a list comprehension with the good_lines list like this:
values = [ l.split()[1] for l in good_lines ]

Python replace word for line [duplicate]

def false_to_true():
name = input("Input name: ")
file=open("users.txt","r")
lines = file.readlines()
file.close()
for line in lines:
username, lel, type = line.split("/")
while name == username:
name = input("input name again: ")
tip = True
with open("users.txt", "w") as users:
users.write(str(red))
#
#I do not know how to perform a given modification and enrollment into place in #the text.
#
#I wont to change word False to True for username i input.
#I have this text in file users:
#Marko123/male/False
#Mimi007/female/False
#John33/male/False
#Lisa12/female/False
#Inna23/female/False
#Alisa27/female/False
I won't to change word False to True for username I input.
I have this text in file users:
Marko123/male/False
Mimi007/female/False
John33/male/False
Lisa12/female/False
Inna23/female/False
Alisa27/female/False
You can just use the csv library and forget about string manipulation:
import csv
def false_to_true():
#read from user.txt file into list(data)
with open('users.txt', 'r') as userfile:
data = [row for row in csv.reader(userfile,
delimiter="/",
quoting=csv.QUOTE_NONE)]
while True:
#waiting for input until you enter nothing and hit return
username = input("input name: ")
if len(username) == 0:
break
#look for match in the data list
for row in data:
if username in row:
#change false to true
row[2] = True
#assuming each username is uniqe break out this for loop
break
#write all the changes back to user.txt
with open('users.txt', 'w', newline='\n') as userfile:
dataWriter = csv.writer(userfile,
delimiter="/",
quoting=csv.QUOTE_NONE)
for row in data:
dataWriter.writerow(row)
if __name__ == '__main__':
false_to_true()
Open the input and output files, make a set out of the user-input names (terminated by a blank line), then create a generator for strings of the proper format that check for membership in the user-input names, then write these lines to the output file:
with open('names.txt') as f, open('result.txt', 'w') as out:
names = {name for name in iter(input, '')}
f = ('{}/{}/{}'.format(a,b,'True\n' if a in names else c) for a,b,c in (line.split('/') for line in f))
output.writelines(f)
To modify a text file inplace, you could use fileinput module:
#!/usr/bin/env python3
import fileinput
username = input('Enter username: ').strip()
with fileinput.FileInput("users.txt", inplace=True, backup='.bak') as file:
for line in file:
if line.startswith(username + "/"):
line = line.replace("/False", "/True")
print(line, end='')
See How to search and replace text in a file using Python?
Ask for name and iterate throw your lines to check for username, like this:
def false_to_true():
name = input("Input name: ")
file=open("users.txt","r")
lines = file.readlines()
file.close()
users = open("users.txt", "w")
for line in lines:
username, lel, type = line.split("/")
if name == username:
type = 'True\n'# \n for new line type ends with '\n'
users.write("/".join([username, lel, type]))
users.close()
false_to_true()

Categories