How to check if an element is not in file? - python

How to check if an element is not in a python File, I tried:
if not element in File.read()
But the "not in" doesn't seems to work I also tried:
if element not in File.read()
Edit: Code Snippet
phone = input('Enter a new number :')
imp = phone
if phone not in phbook.read() and phone_rule.match(imp):
phbook = open('Phonebook','a')
phbook.write('Name: ' + firstname + '\n')
phbook.write('Phone: ' + phone + '\n')
if phone in phbook.read():
print('sorry the user already have this phonenumber ')
else:
if phone_rule.match(imp):
phbook = open('Phonebook','a')
phbook.write('Name: ' + firstname + '\n')
phbook.write('phone: ' + phone + '\n')
print('user added !')
else:
print('This is not a good format')
Not working either

You need to open the file before accessing it.
After reading it, the file cursor is at the end of the file.
You could use phbook.seek(0) to set the cursor at the beginning of the file.
A cleaner way would be to ensure you are using your file only once giving it a better structure, eg:
phone = input('Enter a new number :')
imp = phone
phonebook_filename = 'phonebook.txt'
def ensure_phone_in_phonebook(phone):
with open(phonebook_filename) as phbook:
if phone not in phbook.read() and phone_rule.match(imp):
add_data(firstname, phone)
def add_data(firstname, phone):
with open(phonebook_filename, 'a') as phbook:
phbook.write('Name: ' + firstname + '\n')
phbook.write('Phone: ' + phone + '\n')
ensure_phone_in_phonebook(phone)
Also note the usage of context manager statement with.
It bewares you of closing the file after using.
Further informations

Related

Is there a way to not delete the user input in a text file after running it again?

Whenever I run this program it will ask for a username and a password, store them as the first values in the two lists, open up a text file, and then write password: and username: then whatever username_Database[0] and password_Database[0] are. The problem is when I run the program again, it deletes the previous values. Is there anyway to save the user input and not have it deleted when I run the program again?
import time
username_Database = []
password_Database = []
username = input("Enter a username\n")
username_Database.append(username)
password = input("Enter a password\n")
password_Database.append(password)
print('You are now registered and your user name is \n' + username_Database[0] + "\n and your password is \n" + password_Database[0] + "\n")
print("Saving...")
filename = open("data.txt", "w")
filename.add("Password: " + str(password_Database[0] + "\n"))
filename.add("Username: " + str(username_Database[0] + "\n"))
time.sleep(2)
exit()
You are using write mode when opening the file, it will overwrite everything inside the file. Change it to append mode.
# Using append mode
filename = open("data.txt", "a")
# It should be write instead of add
filename.write ("Password: " + str(password_Database[0] + "\n"))
filename.write ("Username: " + str(username_Database[0] + "\n"))

how to write a header in already existent text file with python

I created a function that appends student's data to a text file. After creating that function I wanted to add a header so that the user would know what the data represents. However now, the header is indeed added to the file, but the function does not add the student's data anymore...
Here is my code:
FirstName = []
LastName = []
Class = []
Adress = []
Math = []
Science = []
English = []
Dutch = []
Arts = []
def add_records(filename, FirstName, LastName, Class, Adress, Math, Science, English, Dutch, Arts):
header = "First Name, Last Name, Class, Adress, Math Grade, Science Grade, English Grade, Dutch Grade, Arts Grade"
x= input("Enter First Name:")
FirstName.append(x)
y=input("Enter Last Name:")
LastName.append(y)
b=input("Enter Student's Class:")
Class.append(b)
o=input("Enter Address:")
Address.append(o)
z=int(input("Enter Math Grade:"))
Math.append(z)
w=int(input("Enter Science Grade:"))
Science.append(w)
h=int(input("Enter English Grade:"))
English.append(h)
p=int(input("Enter Dutch Grade:"))
Dutch.append(p)
v=int(input("Enter Arts Grade:"))
Arts.append(v)
f = open(filename, 'r')
lines = f.readlines()
if lines[0] in f == header:
f=open(filename,"a+")
for i, j, r, k ,l, m, n, o, p in zip(FirstName, LastName, Class, Adress, Math, Science, English, Dutch, Arts):
print(i,j,k,r,l,m,n,o,p)
a=f.write(i + ' ' + j + ' ' + r + ' '+ k + ' ' + str(l) + ' ' + str(m) + ' ' + str(n) + ' ' + str(o) + ' ' + str(p) + "\n")
f.close()
else:
file = open(filename, 'a+')
file.write(header + a + "\n")
file.close()
f.close()
add_records("mytextfile.txt",FirstName,LastName,Class,Adress,Math,Science,English,Dutch,Arts)
Could someone explain to me why?
In case the mytextfile.txt has not been created yet, it will throw an error. If you already created the empty mytextfile.txt, then it still throws an error because there is no lines[0] (it's an empty file).
And your if statement has a problem too, you should write:
if lines[0].strip() == header
text files do not have a header. If you want a true header, you'll need a more complex format. Alternatively, if you just need something that acts like a header, then you need to figure out how many characters fit on your page vertically, and print the header every N lines.
For horizontal alignment, make use of the extra tokens you can use with format(). As an example:
print('{a:^8}{b:^8}{c:^8}'.format(a='this', b='that', c='other'))
this that other
where ^8 says I want the string centered across 8 characters. Obviously you have to choose (or derive) the value that works for your data.

How would I print the fav_genre field for a specific user

So the code below saves the variables username pass etc into a text file with the colons to separate each field. say I wanted to print out the favourite genre of a particular user, how would that be possible as my attempts so far to do so have failed. this is all in python btw. ive edited to add my attempt but its not woking.Any ideas??
usrFile_write = open(textfile, 'a')
usrFile_write.write(username + ' : ' + password + ' : ' + name + ' : ' + dob + ' : ' + fav_artist + ' : ' + fav_genre + ' : ' + '\n')
print('New Account Created!')
print()
usrFile_write.close()
Menu()
my attempt:
textfile = 'user_DB.txt'
username = 'dj'
def getUsersFavouriteGenre():
with open(textfile, 'r') as textIn:
for line in textIn:
information = line.split(' : ')
if information[0] == username:
return information[5]
return 'Failed to find user.'
getUsersFavouriteGenre()
Your code looks good. I'm assuming the issue is your program doesn't output anything, in which case the only issue I see is change your last line getUsersFavouriteGenre() to print(getUsersFavouriteGenre())
If you are getting a specific error or undesired output then you can let us know and we can help you more specifically.

How would I overwrite the fav_genre of the user in this code

So I'm developing a code for a very basic music app, Every users information is saved into the database using the following format:
usrFile_write.write(username + ' : ' + password + ' : ' + name + ' : ' + dob + ' : ' + fav_artist + ' : ' + fav_genre + ' : ' + '\n' )
now I want to read the existing information of a particular user and allow them to change their fav_genre. Below is my failed attempt to do so:
textfile = 'user_DB.txt'
def a():
username = input('name?: ')
with open(textfile, 'r+') as textIn:
for line in textIn:
information = line.split(" : ")
if information[0] == username:
print('Your current genre is:',information[5])
new_genre = input('what would you like your new genre to be?')
information[5] = new_genre
textIn.write(information[5]=new_genre)#this line
print('new genre is saved to',information[5])
break
elif information != username:
print('Name not found, Please try again')
a()
else:print('invalid')
break
textIn.close()
a()
The line with the comment #this line is where I think the error is occouring as I want to overwrite the previous value of fav_genre for that specific user with the new one.Any ideas on what I could do different to make this work?
Basically change that line to:
textfile.write(' : '.join(information.values()) + '\n' )
So full code:
textfile = 'user_DB.txt'
updated_textfile = 'user_DB_Updated.txt'
def a():
username = input('name?: ')
updated_lines = []
with open(textfile, 'r+') as textIn:
for line in textIn:
information = line.split(" : ")
updated_lines.append(line)
if information[0] == username:
print('Your current genre is:',information[5])
new_genre = input('what would you like your new genre to be?')
information[5] = new_genre
updated_lines[-1] = ' : '.join(information) + '\n'
print('new genre is saved to ',information[5])
break
elif information != username:
print('Name not found, Please try again')
a()
else:print('invalid')
break
with open(updated_textfile, 'w+') as out_text:
out_text.write(''.join(updated_lines))
textfile.close()
a()

Reading two consecutive lines in Python if one starts with a specific string

I am currently trying to learn Python. I know some basics and I'm trying to practise by making a game. My code so far is:
import time
import datetime
now = datetime.datetime.now()
name = input('What is your name? >> ')
file = open("users.txt","+w")
file.write(name + ' started playing at: ' + now.strftime("%Y-%m-%d %H:%M") + '. \n')
file.close()
account = input('Do you have an account ' + name + '? >> ')
while(account != 'yes'):
if(account == 'no'):
break
account = input('Sorry, I did not understand. Please input yes/no >> ')
if(account == 'yes'):
login = input('Login >>')
passwd = input('Password >>')
if login in open('accounts.txt').read():
if passwd in open('accounts.txt').read():
print('Login Successful ' + login + '!')
else:
print('Password incorrect! The password you typed in is ' + passwd + '.')
else:
print('Login incorrect! The login you typed in is ' + login + '.')
As you probably noticed I am working on a login system. Now please ignore all the bugs and inefficient code etc. I want to focus on how I can get Python to check for a line in a .txt file and, if it's there, check the one below.
My .txt file is:
loggn
pass
__________
I want to make the program multi-account. This is why I am using a .txt file. If you need me to clarify anything, please ask. Thankyou! :)
with open('filename') as f:
for line in f:
if line.startswith('something'):
firstline = line.strip() # strip() removes whitespace surrounding the line
secondline = next(f).strip() # f is an iterator, you can call the next object with next.
Store the results of "open('accounts.txt').read()" yourself, and iterate over them as an array - if you know what line number you are on, it is trivial to check the next. Assuming that every even numbered line is a login, and every odd numbered line is a password, you would have something like this:
success = False
# Storing the value in a variable keeps from reading the file twice
lines = open('account.txt').readlines()
# This removes the newlines at the end of each line
lines = [line.strip() for line in lines]
# Iterate through the number of lines
for idx in range(0, len(lines)):
# Skip password lines
if idx % 2 != 0:
continue
# Check login
if lines[idx] == login:
# Check password
if lines[idx + 1] == password:
success = True
break
if success:
print('Login success!')
else:
print('Login failure')
You may also consider changing your file format: using something that won't occur in the login name (such as a colon, unprintable ASCII character, tab, or similar) followed by the password for each line means you could use your original approach by just checking for (login + "\t" + password) for each line, rather than having to worry about having two lines.

Categories