Update single field in text file python - python

I have this function:
def favourites():
name = input("Enter your name as you did when you signed up: ")
new_artist = input("Would you like to edit your favourite artist? y/n ").lower().strip()
if new_artist == 'yes' or new_artist == 'y':
old_artist = input("Enter the favourite artist you used when signing up: ")
artist = input("Enter your new favourite artist: ")
usersFile = open('users.txt', 'r+')
usersRec = usersFile.readline()
# reads each line in the file
while usersRec != "":
# splits each record into fields
field = usersRec.split(',')
if field[0] == name:
usersFile.write(field[2].replace(old_artist, artist))
usersRec = usersFile.readline()
usersFile.close()
I have read a line in the text file and then split it into fields and i want to update a single field. Searched and found the update() function so tried that but it doesn't work and i'm not sure what i'm doing wrong. Any suggestions?

You should write to file in another stream, opening file for writing. Also made some corrections in readlines() method and 'replace' part (you should put the result into variable which is field[2]):
import io
import sys
def favourites():
content=[]
name = input("Enter your name as you did when you signed up: ")
new_artist = input("Would you like to edit your favourite artist? y/n
").lower().strip()
if new_artist == 'yes' or new_artist == 'y':
old_artist = input("Enter the favourite artist you used when signing
up: ")
artist = input("Enter your new favourite artist: ")
with open('users.txt', 'r+') as usersFile:
usersRec = usersFile.readlines()
print(usersRec)
# reads each line in the file
for ur in usersRec:
# splits each record into fields
field = ur.split(',')
if field[0] == name:
field[2] = field[2].replace(old_artist, artist)
content.append(','.join(field))
else:
content.append(','.join(field))
usersRec = usersFile.readline()
usersFile.close()
writeToFile(content)
def writeToFile(content):
with open('users.txt', 'w+') as usersFile:
for line in content:
usersFile.write(line)
usersFile.close()
if __name__=="__main__":
favourites()

Related

How am i able to search for inputs in a file and print them in a function

The Springfork Amateur Golf Club has a tournament every weekend. The club president has asked you to write four programs:
A. A program that will read each player's name and golf score as keyboard input, the save these records in a file named golf.txt.(Each record will have a field for the player's name and a field for the player's score)
B. A program that reads the records from the golf.txt file and displays them.
C. A program that searches for a particular record when player's name is given.
D. A program that modifies score of a player.
I've got the first 2 parts down but struggling to complete part C and D
This is what I have so far
def main():
move_on = 'y'
golfScoreFile = open('golfRecords.txt', 'a')
while move_on == 'y' or move_on == 'Y':
pName = input("Enter the player's name: ")
pScore = int(input("Enter the player's score: "))
golfScoreFile.write(pName + "\n")
golfScoreFile.write(str(pScore) + "\n")
move_on = input("Would you like to continue? [y]: ")
displayRecords = input("Would you like to display all the records from golfRecords.txt? [y]: ")
golfScoreFile.close()
if (displayRecords == 'y' or displayRecords == 'Y'):
displayRecs()
else:
searchRecs()
def displayRecs():
golfScoreFile = open('golfRecords.txt', 'r')
lineCount = 1
for line in golfScoreFile:
golfRecLine = lineCount % 2
if (golfRecLine == 0):
print("The score of this person is: ", line)
if (golfRecLine == 1):
print("The name of this person is: ", line)
lineCount = lineCount + 1
golfScoreFile.close()
def searchRecs():
search = input("Enter players name to search: ")
def modscore():
main()
print('Please paste your saved file code:')
file_load_code = input('')
file = open('logs.txt', 'r')
logs = file.read()
if file_load_code in logs:
print('Finding file...')
time.sleep(0.2)
print('Found!')
print('Press enter to fully load the file:')
ENTER = input('')
file.close()
file = open('file_context.txt', 'r')
for x in file:
if file_load_code in x:
print(x)
Try that!

comparing user input to text file

from pip._vendor.distlib.compat import raw_input
class Login:
def logging_in(self):
StudentID = raw_input("please enter your student id. ")
f = open("StudentDetails.txt", "r+")
lines = f.readlines()
if StudentID == lines:
print("Verified Welcome")
else:
print("you are not a registered Student Goodbye")
f.close()
login = Login()
login.logging_in()
I'm atempting to compare my user input to my variables inside the text file. Every time I atempt to type in a student id (0001,0002) It keeps Printing the you are not a registered student goodbye. How to resolve this?
You can load the valid IDs once when the instance is created. Then when a user tries to login, you just check if the ID exists in that set. For example:
from pip._vendor.distlib.compat import raw_input
class Login:
def __init__(self):
with open("StudentDetails.txt", 'r') as file:
lines = file.readlines()
self.valid_ids = set([s.strip() for s in lines])
def logging_in(self):
StudentID = raw_input("please enter your student id. ")
if StudentID.strip() in self.valid_ids:
print("Verified Welcome")
else:
print("you are not a registered Student Goodbye")
login = Login()
login.logging_in()
You're comparing input ID against a list, you need add a for loop
def logging_in(self):
StudentID = raw_input("please enter your student id. ")
f = open("StudentDetails.txt", "r+")
lines = f.readlines()
for line in lines
if StudentID in line:
print("Verified Welcome")
else:
print("you are not a registered Student Goodbye")
f.close()
BTW, as #Cohan says in comments, any character in line will give access to user. I am assuming this is just for learning purposes, and not a real security approach.

Existing file not appending new record

I am trying to create a file as the header and then open it later to append new records, but it seems I am not doing something correctly, does anyone have an idea?
here is the code below:
I have tried it in several ways to no avail.
file = 'Quizdata5.txt'
users = {}
def header():
headers = ("USERID LOGIN-NAME SURNAME NAME AGE "
" YEAR-GROUP SEX USERNAME\n")
with open(file, 'w') as file1:
file1 .write(headers)
file1.close()
def newUser():
global users
global header
global createLogin
global createPassw
global surname
global name
global age
global y_group
global sex
global z1
createLogin = input("Create login name: ")
if createLogin in users: # check if login name exists
print("\nLogin name already exist, please choose a different name!\n")
else:
createPassw = input("Create password: ")
users[createLogin] = createPassw # add login and password
#return (users[createLogin])
surname = input("Pls enter your surname: ")
name = input("Pls enter ur name: ")
age = input("Pls enter your age: ")
y_group = int(input("Please enter your year group: "))
sex =input("Please enter your sex: ")
print("\nUser created!\n")
print("*********************************")
print(" Your Name is\t" + name, "and it starts with: " + name[0] + "\n")
z1 = createPassw[:3] + age
print(" Your Username is:\t ", z1)
if __name__ =='__main__':
header()
while newUser():
with open(file, 'a') as file2:
rows = ("{:8} {:8} {:8} {:8} {:8} {:8}"
" {:8} {:8} \n".format(createLogin, createPassw,
surname, name, age,
y_group, sex, z1))
file2.write(rows.split())
file2.close()
#enter code here
Working version below. Note that I changed your input statements to raw_input. I'm using Python 2.7. Main things needed:
a choice to exit outside AND inside the while loop
build a list for existing users for the existing username check
fixing your formatting for row
Not splitting your row when you write it
Seems to be working now and ready for more improvements. Build a little and test until working, then build more - saves a ton of time!
file = 'Quizdata5.txt'
users = {}
def header():
headers = "USERID LOGIN-NAME SURNAME NAME AGE YEAR-GROUP SEX USERNAME\n"
with open(file, 'r') as file1:
firstLine = file1.readline()
print firstLine
if firstLine == headers:
print 'Headers present'
return
with open(file, 'w') as file1:
file1.write(headers)
def newUser():
userList = []
with open(file, 'r') as file1:
Lines = file1.readlines()
for line in Lines[1:]:
lineArray = line.split(' ')
userList.append(lineArray[0])
print userList
global users
global header
global createLogin
global createPassw
global surname
global name
global age
global y_group
global sex
global z1
createLogin = raw_input("Create login name or enter 'exit' to quit: ")
if createLogin == 'exit':
return False
while createLogin in userList: # check if login name exists
print("\nLogin name already exist, please choose a different name!\n")
createLogin = raw_input("Create login name or enter 'exit' to quit: ")
createLogin = createLogin.strip()
if createLogin == 'exit':
print('Goodbye for now.')
return False
createPassw = raw_input("Create password: ")
users[createLogin] = createPassw # add login and password
# return (users[createLogin])
surname = raw_input("Pls enter your surname: ")
name = raw_input("Pls enter ur name: ")
age = raw_input("Pls enter your age: ")
y_group = int(raw_input("Please enter your year group: "))
sex = raw_input("Please enter your sex: ")
print("\nUser created!\n")
print("*********************************")
print(" Your Name is\t" + name, "and it starts with: " + name[0] + "\n")
z1 = createPassw[:3] + age
print(" Your Username is:\t ", z1)
return True
if __name__ =='__main__':
header()
while newUser() == True:
with open(file, 'a') as file2:
row ="{a} {b} {c} {d} {e} {f} {g} {h}\n".format(
a=createLogin, b=createPassw, c=surname, d=name, e=age, f=y_group, g=sex, h=z1)
file2.write(row)
Without just rewriting your code outright, your problem is the line
while newUser():
This means call newUser(), and execute the indented code only if the return value of newUser(), evaluated as a boolean, returns True. That is bool(newUser()) is True.
Now the questions are
a) What does newUser() return and,
b) What does bool() mean?
First b: All objects in Python have some "boolean" value associated with it, True or False. For a lot of built-in types their boolean evaluation makes sense. For example the integer 0 is treated as False in a boolean context, while any non-zero integer is treated as True. This is the case in most any programming language with some exceptions.
Similarly an empty list [] is False in a boolean context (which is why we can write things like if not my_list: ... to test if a list is empty) while any non-empty list is treated as True and so on.
As for a:
Your newUser() function doesn't explicitly return and any result, because you don't have a return statement (Tom's solution added some). What you want to do is return a True-ish value when a new user is added, and a False-ish value when no new users are to be added. But since you don't return anything, in fact, the default return value for functions if Python, if you don't explicitly return, is a value called None and it is always False.
So the end result is that the code under your while statement is never run.
If you're ever in doubt about what your code is doing walk through it line by line and see exactly what it's doing--what functions are returning and what values are being assigned to variables--by using the pdb debugger (Google will direct you quickly to some good tutorials). With Python in particular there's no reason to ever be in the dark about what your code is actually doing.

How can you use a while loop so the user can open a new text file? Python

I want to use a while loop that will give the user an opportunity to open a new text file at the end of the program. Here is the code I have:
run_again = "yes"
run_again = run_again.upper().strip()
while run_again == "yes":
open_file = input("Please enter name of file: ")
file_name = open(open_file,"r")
for line in file_name:
line = line.strip()
rows = line.split(" ")
num = rows[0]
print(num)
run_again = input("Would you like to open a new file (yes or no)? ")
if run_again != "yes":
print("Have a great day!")
I've managed to make a while loop work with other code but I can't get it to work with opening text files.
I think something like that would work. Can't really test now.
run_again = True
while run_again:
open_file = input("Please enter name of file: ")
file_name = open(open_file,"r")
for line in file_name:
line = line.strip()
rows = line.split(" ")
num = rows[0]
print(num)
if input("Would you like to open a new file (yes or no)? ") != "yes":
print("Have a great day!")
break
Edit :
As suggested by Blorgbeard :
while True:
open_file = input("Please enter name of file: ")
file_name = open(open_file,"r")
for line in file_name:
line = line.strip()
rows = line.split(" ")
num = rows[0]
print(num)
if input("Would you like to open a new file (yes or no)? ") != "yes":
print("Have a great day!")
break

How would I tell Python to read my text file?

def inputbook():
question1 = input("Do you want to input book?yes/no:")
if question1 == "yes":
author = input("Please input author:")
bookname = input("Please input book name:")
isbn = input("Please input ISBN code")
f = open("books.txt", "a")
f.write("\n")
f.write(author )
f.write(bookname )
f.write(isbn )
f.close()
elif question1 == "no":
input("Press <enter>")
inputbook();
So I have code like this and I when I write last string (isbn), and I want python to read books.txt file. How am i supposed to do it?
There are problems with your open, which renders it unreadable.
You need to open it with:
f = open("books.txt", "+r")
"a" stands for appending, so you won't be able to read books.txt with f.
Second, readlines or readline are not good options for your code as of now. You need to update your write method. Since inside the .txt file, the author, bookname and isbn will be messed together, and you are not able to separate them.
def inputbook():
question1 = raw_input("Do you want to input book? (yes/no):")
if question1 == "yes":
author = raw_input("Please input author:")
bookname = raw_input("Please input book name:")
isbn = raw_input("Please input ISBN code:")
f = open("books.txt", "a+")
f.write("%s | %s | %s\n" % (author, bookname, isbn))
f.close()
elif question1 == "no":
raw_input("Press <enter>")
try:
print open('books.txt', 'r').read()
except IOError:
print 'no book'
if __name__ == '__main__':
inputbook()

Categories