input in a function and remove lines from a file - python

I'm trying to make a modules and for one of the commands I need it to remove a specified user. I need help with it finding the line the user is at. Then deleting the username. Here is the code.
def delete_usr(usr):
file = open("Username.txt","r+")
count = 0
userfound = False
try:
for user in file.readlines():
count += 1
if usr == user.strip():
userfound = True
BTW i also need it to delete the password. The password has the same line as the username and is kept in password.txt

The closest solution to your suggestion would be:
def delete_usr(usr):
file = open("Username.txt","r+")
count = 0
userfound = False
for user in file.readlines():
#print(user.strip())
count += 1
if usr == user.strip():
userfound = True
#print("yeah")
#break
file.close()
If you use a try statement, you expect a perticular kind of error (eg. key not in a dictionary) and also should write except statement to catch the error.
If you use open(file), it is a good practice to also use file.close(). If you use the with statement, as in the example above, you don't need to do it as it is done automatically.

This should do the trick (as long as the user is only on a single line, else remove the break statement):
def delete_usr(usr):
with open("Username.txt","r") as myfile:
lines = myfile.readlines()
for idx, l in enumerate(lines):
if usr==l.split(':')[0]:
lines[idx] = ''
break
with open("Username.txt","w") as myfile:
[myfile.write(i) for i in lines]

Related

Why is my code not able to find the input number in the file even if the input number is clearly present in the file?

This is the code to search a particular entry in a file:
num2find = str(input("Enter a number to find: "))
test_file = open("testfile.txt", "r")
num = "0"
flag = False
while (num != ""):
num = test_file.readline()
if (num == num2find):
print("Number found.")
flag = True
break
if not flag:
print("\nNumber not found.")
The test file is:
1
2
3
4
5
If I input 2, the code still outputs "Number not found."
Every time you read a line from a text file, you are getting "\n" at the end of the string line, so the problem you are facing is that you are comparing "2" to "2\n" which is not the same.
You could take advantage of with to pen your file. This way you do not need to worry about closing the file once you are done with it. Also, you do not need to pass the "r" argument since it is the default mode for open.
You should use a for loop instead of that needless while loop. The for loop will terminate automatically when all the lines in the file have been read.
One more improvement you could make is to rename the flag flag to found, and to print the result once the file has been processed.
num2find = int(input("Enter a number to find: "))
found = False # rename flag
with open("testfile.txt") as test_file: # use with to avoid missing closing the file
for line in test_file: # use a for loop to iterate over each line in the file
num = int(line)
if num == num2find:
found = True
break
if found: # print results at the end once file was processed
print("Number found.")
else:
print("Number not found.")
Each line in the test file contains two characters - the number and a newline. Since "2" does not equal "2\n", your number is not being found. To fix this, use the int function to parse your lines, since it ignores whitespace (like the \n) character:
num2find = int(input("Enter a number to find: "))
flag = False
with open("testfile.txt", "r") as test_file:
for line in test_file:
num = int(line)
if num == num2find:
print("Number found.")
flag = True
break
if not flag:
print("\nNumber not found.")
The easiest and the most logical solution I could come up with after all the feedback was this:
num2find = int(input("Enter a number to find: "))
file_data = open("testfile.txt", "r")
found = False
for data in file_data:
if int(data) == num2find:
found = True
if found:
print("\nNumber found.")
else:
print("\nNumber not found.")
file_data.close()
You need to add .rstrip() on num = test_file.readline()
Try something like this:
num2find = str(input("Enter a number to find: "))
test_file = open("testfile.txt", "r")
file_data = test_file.readlines()
flag = False
for item in file_data:
if num2find == item.rstrip():
flag = True
break
if not flag:
print("\nNumber not found.")
else:
print("Number found")
Don't use .readline() like that, use readlines() instead

Search content from a file dictionary in python

I have file (dictionary) and I want to search a specific content from a file, how to write the query?
def name_search():
target = open("customers.txt",'r')
name_search = input('Search >')
for line in target:
if name_search in line:
print(f'{name_search} in record!')
else:
print('Not in record!')
The above code works, however, it tries to print this line multiple times depending how many lines I have in file. Assuming the line is not present:
Not in record!
Not in record!
Not in record!
Not in record!
If you are saying you do not want to print multiple times, only once at the end of reading the whole file, then do something like this:
def name_search():
target = open("customers.txt",'r')
name_search = input('Search >')
found = False # use this to remember if we found something
for line in target:
if name_search in line:
print(f'{name_search} in record!')
found = True # remember we found it!
break # this kicks you out of the loop, so you stop searching after you find something
if not found:
print('Not in record!') # only prints this if we didn't find anything
Alternatively, and in fewer lines of code, you can use a return statement in the "found" case. There are reasons people like to avoid having multiple return points in their code, but I present it here as an option:
def name_search():
target = open("customers.txt",'r')
name_search = input('Search >')
for line in target:
if name_search in line:
print(f'{name_search} in record!')
return # kicks us out of the function after we find something
print('Not in record!') # still only prints this if we didn't find anything

Python error list index out of range when reading from CSV

Hey I am trying to read data from a list that is from a CSV file
def Load(): #Loads data from the csv that can be stored in functions
global userdata
global user
userdata = []
f = open('userdata.csv','r')
data = csv.reader(f)
for row in data:
user = []
for field in row:
user.append(field)
userdata.append(user)
f.close()
This is the login function which I am looping over
def Login(): #Login function
global userdata
Load()
global user
print('Please now login to your account')
x = False
while x == False:
usernameLog = input('Please enter your username: ')
j = len(userdata)
for i in range(0,j):
if usernameLog == userdata [i][0]: #Validates username
print('Username accepted')
time.sleep(1)
My program successfully writes to the CSV but just doesn't read from it without throwing out this error. I might just be being stupid though.
You have the line user = [] inside the for loop, so you are always "cleaning" user before appending the new value, so only the last value is added, and the previous one is removed.
You should take it out of the loop, the same you are doing with userdata.
(This is what it looks like, unless your csv structure is totally different and you don't need one user per one userdata)

How to fix EOF error when reading user input in python 3?

I need to read multiple lines from user input, parse them as commands and call functions. I keep getting EOFError even after I have threw an exception. Same thing happens if I put the if..else statements inside 'try'. The program stops at main and wouldn't call the functions.
EDITED
infile = open('file.csv')
weather = list()
for line in infile:
parse_one_line() #parse each row into tuples
#and add them into a list
while True:
try:
input_stream = input()
command = input_stream.split()
except ValueError:
pass
if command == []:
pass
elif command[:4] == ['filter', 'TEMP', 'at', 'least']:
filterRecord() #user input "filter TEMP at least <integer>"
elif ...
def filterRecord(): #filter rows that meet
#the criteria into a new list
global filtered
filtered = list()
try:
for x in range(len(weather)):
if int(weather[x][2]) >= int(command[-1]):
print(weather[x])
filtered.append(tuple(weather[x]))
except ValueError:
pass
The problem is probably with this line
elif: command == '..'
The colon is in the wrong place, change it to
elif command == '..':

Python Spell Check With Suggestions

I have a program that I'm working on that takes an input and checks it to see if it spelled correctly with a dictionary inside of a file. However, I want to return a suggestion or two as well of what the person means. Any suggestions of how to do this? I have found some modules that can do it, but not for a specific dictionary from a file. Any help is appreciated!!
Here is what I have now:
def getDictionary():
theDictionary = open("theDictionary.txt", "r")
dictionaryList = []
for eachLine in theDictionary:
splitLines = eachLine.split()
dictionaryList.append(splitLines[0])
theDictionary.close()
return dictionaryList
def spellChecker(theFile, theDictionary):
lowerItems = theFile.lower()
wordList = lowerItems.split()
wrongList = []
for item in wordList:
if item not in theDictionary:
result = False
wrongList.append(item)
else:
result = True
wrongItem = ""
return (result, wrongList)
def main():
theDictionary = getDictionary()
theText = getFile()
theInput = input("Input some words here:")
result, wrongList=spellChecker(theInput,theDictionary)
if result:
print("There are no spelling errors in the sentence! Hooray!")
else:
if len(wrongList) == 1:
print('There is a spelling error in the sentence! The word that is wrong is "' + str(wrongList) + '".')
elif len(wrongList) > 1:
print('There are some spelling errors in the sentence! The words that are wrong are"' + str(wrongList) + '".')
main()
You might want to have a look at the difflib module in the Standard Library. It allows you to do approximate string matching, which seems to be what you want.
It really does not matter if your dictionary is inside a file or not, since you are loading it into a list anyway. Maybe have a look at the get_close_matches() method in the said module.

Categories