Read the 3 next lines in python file - python

I want to read the 3 next lines in a file but from a given point
If a user is in the phonebook I display the user and the 3 next lines -> code snippet
import re
phonebook_rule = re.compile(r'\'\D{3,6}\'\'\D{3,13}\'\'\d{10}\'')
def myFunction(phonebooke):
print(phonebooke)
if begin == 1:
firstname = input('enter a firstname:')
lastname = input('enter a lastname:')
phone = input('enter a number:')
imp = (f'\'{firstname}\'\'{lastname}\'\'{phone}\'')
if phonebook_rule.match(imp):
phbook = open('Phonebook','a')
phbook.write('Fristname: ' + firstname + '\n')
phbook.write('Lastname: ' + lastname + '\n')
phbook.write('Phone: ' + phone + '\n')
phbook.close()
else:
print('Not a good format')
elif begin == 2:
search = input('Search a user:')
cnt = 1
if search in phbook.read():
print('This user is in the phonebook')
while True:
print(phbook.readlines())
cnt += 1
if cnt == 3:
break
else:
print('No user found')
else:
print('nothing')
begin = int(input('Chose a number 1 to 4:'))
print(myFunction(begin))
Don't know how to do this , especially the part when I need to start from "search" input and then display the 3 other lines...
Edit:
That's the only things I get with readlines()
There's a user called Matt in my phonebook or maybe I did something wrong ?

It might help to reinitialize the file object. I suspect that this is will do what you're looking for.
search = input('Search a user:')
phbook.close()
phbook = open('Phonebook','r')
for line in phbook:
line = line.strip()
if search in line:
print('This user is in the phonebook')
print(line) # print the line where you found the string
for _ in range(2):
print(phbook.readline()) # print the next 2 lines
break
else:
print('No user found')

Related

How to read and write on this file?

I have to write a code that does the following:
Create a menu with three options.
Print the subjects
Search for a subject
Q) Quit
Create a main() function
Prompt the user for a file name.
Prompt the user for an option from the menu.
Open the file and load the data into a list.
Option 1 should print all the school subjects in the list, under a title
Once all the records have been processed, print a count.
Option 2 should allow the user to search for a subject in the list.
Add exception handling. (add last)
Create your own text file, with a list of 10 or more school subjects.
Submit the program module(s) and the output.
For a bonus, create a second module and import it, or add a menu item to add names to the list and save the data to a new file.
I keep getting "file not found" and was wondering if anyone could help. I want to name the read file as subjects.txt
This is the code I have written:
#Display menu and ask for user to select option
def menu():
print('Enter "1" to print subjects')
print('Enter "2" to search subjects')
print('Enter "3" to add subject')
print('Enter "q" to quit')
option = input('Enter option: ')
return option.lower()
#Reading files
def read_subjects(file_name):
file1 = open(subjects, 'r')
return file1.readlines()
#Add new subjects
def write_to_file(file_name, subject):
current_lines = []
try:
current_lines = read_subjects(file_name)
except:
pass
current_lines.append(subject + '\n')
file1 = open(file_name, 'w')
file1.writelines(current_lines)
file1.close()
#Main function
def main():
correct_file_name = False
file_name = 'subjects'
subjects = []
# while loop to ensure a user selects an existing file with catch and try
while not correct_file_name:
file_name = input('Enter file name: ')
try:
subjects = read_subjects(subject)
correct_file_name = True
except:
print('Error file not found')
# while loop to implement contious flow of options
while True:
selected_option = menu()
# quit program
if selected_option == 'q':
quit()
# display subjects
if selected_option == '1':
print('Subjects')
# Strips the newline character
count = 0
for line in subjects:
count += 1
print("{}: {}".format(count, line.strip()))
print('Total subjects: ', count)
print('==============================================')
# search for a subject
if selected_option == '2':
subject = input('Search subject: ')
print('Subjects')
count = 0
for line in subjects:
striped_line = line.strip()
if subject.lower() in striped_line.lower() or striped_line.lower() in hobby.lower():
count += 1
print("{}: {}".format(count, line.strip()))
print('Total subjects: ', count)
print('==============================================')
# bonus add new hobbies
if selected_option == '3':
subject = input('Enter new hobby: ')
write_to_file('subjects.txt', subject)
# call main function
if __name__ == '__main__':
main()

How to import content from a text file and add them to variables

I have a settings file for a monopoly like game I'm making, the settings file has parameters like the number of people playing and whatnot, I would like to know how to import the settings from that text file and bring it into different variables, for example, having number of players in the settings file go to a numPlayers variable in the actual code so I can use it for other games and also usee the settings in the code
This is my code:
def inputs(line, typeinp=None, start=None, end=None):
while True:
string = input(line)
if typeinp != None:
try:
if typeinp == "string":
string = str(string)
elif typeinp == "integer":
string = int(string)
if start != None and end != None:
while not (string >= start and string <= end):
print("Please input a number between", str(start) + "-" + str(end))
string = int(input(line))
break
except:
print("Plese input a", typeinp)
else:
break
return string
# Settings file, if user chooses to run setup this is all the setup questions
def gameSettingsSetup():
settingsCheck = open("settings.txt", "r")
print("Lets setup")
# Int Setup questions
numPlayers = str(inputs('How many real players are playing: ', "integer"))
numAIplayers = str(inputs('How many AI players will be playing?: ', "integer"))
AILevel = str(inputs("What AI difficulty level would you like? (Easy, Normal, Hard): "))
while True:
if AILevel == "Easy" or AILevel == "Normal" or AILevel == "Hard":
startingMoney = str(inputs("How much money does everyone start with? Max: 10 000 (Keep in mind "
"this does not affect the property prices) ", "integer", 100, 10000))
break
else:
print("Please enter a valid input (make sure to capitalize the first letter)")
AILevel = str(inputs("What AI difficulty level would you like? (Easy, Normal, Hard): "))
# sends over the settings into the text file as well as monoset check
if "MonoSet1-1" in settingsCheck.read():
with open("settings.txt", "w") as file:
file.write("MonoSet1-1: true" + "\n")
file.write("numPlayer: " + numPlayers + "\n")
file.write("numAIplayer: " + numAIplayers + "\n")
file.write("AI Level: " + AILevel + "\n")
file.write("startingMoney: " + startingMoney + "\n")
file.close()
# Allows for access to the settings file and drops values into a list
settings = []
with open("settings.txt") as file:
for line in file:
line = line.split(":")
line = line[1]
line = line.rstrip("\n")
line = line[1:]
line = line.split(" ")
try:
for x in range(len(line)):
line[x] = int(line[x])
line = (line[0], line[1])
except:
line = line[0]
settings.append(line)
file.close()
print("Alright the setup is complete, Your game will start now....")
time.sleep(1)
return settingsCheck, settings

No attribute present

I am quite new to python and I am getting an attribute error.
import FileHandeling as fh;
import os;
CounterFilePath = os.path.dirname(os.path.realpath(__file__))+"/counter.txt";
FilePath = os.path.dirname(os.path.realpath(__file__))+"/FileIO.txt";
class Employee:
def createEmployee(self):
numOfEmployees = int(input("Enter number of employees: "));
empDetails = [];
for i in range(numOfEmployees):
empFName, empLName, empSalary, empEmailId = raw_input("Enter employee first name: "), raw_input("Enter employee last name: "), raw_input("Enter employee salary: "), raw_input("Enter employee Email ID: ");
string = str(i)+" "+empFName+" "+empLName+" "+empSalary+" "+empEmailId+"\n";
empDetails.append(string);
with open(FilePath,"a+") as fo:
fo.seek(0);
fh.createFile(fo,numOfEmployees,empDetails,CounterFilePath);
def searchEmployee(self):
choice = int(input("Press:\n1 to search by First Name\n2 to search by Last Name\n3 to search by Salary\n4 to search by Email ID\n"));
print "Enter the",;
if(choice == 1):
print "First Name:",;
elif(choice == 2):
print "Last Name:",;
elif(choice == 3):
print "Salary:",;
elif(choice == 4):
print "Email ID:",;
searchStr = raw_input();
with open(FilePath,"r") as fo:
string = fh.readFile(fo,searchStr,choice-1);
while line in string:
print line;
def updateEmployee(self):
print "Leave the entries empty if you dont want to update that entry.";
lineNum = input("Enter the line number of the entry you want to update: ");
with open(FilePath,"r") as fo:
empFName, empLName, empSalary, empEmailId = raw_input("Enter employee first name: "), raw_input("Enter employee last name: "), raw_input("Enter employee salary: "), raw_input("Enter employee Email ID: ");
if(empFName == ""):
record = fh.readFile(fo,lineNum-1,0);
empDetails = record[0].split();
empFName = empDetails[1];
if(empLName == ""):
record = fh.readFile(fo,lineNum-1,0);
empDetails = record[0].split();
empLName = empDetails[2];
if(empSalary == ""):
record = fh.readFile(fo,lineNum-1,0);
empDetails = record[0].split();
empSalary = empDetails[3];
if(empEmailId == ""):
record = fh.readFile(fo,lineNum-1,0);
empDetails = record[0].split();
empEmailId = empDetails[4];
updateStr = str(lineNum-1)+" "+empFName+" "+empLName+" "+empSalary+" "+empEmailId+"\n";
fh.updateRecord(fo,FilePath,updateStr,lineNum-1);
def deleteEmployee(self):
lineNum = input("Enter the line number of the entry you want to delete: ");
with open(FilePath,"r") as fo:
fh.deleteRecord(fo,FilePath,lineNum-1);
def main(self):
goOn = True;
employee = Employee();
while goOn:
choice = input("Press:\n1 to enter a new employee\n2 to search employee\n3 to update employee\n4 to delete employee\n0 to exit\n");
if(choice == 1):
employee.createEmployee();
elif(choice == 2):
employee.searchEmployee();
elif(choice == 3):
employee.updateEmployee();
elif(choice == 4):
employee.deleteEmployee();
elif(choice == 0):
goOn = False;
else:
print "Wrong Choice!!!";
emp = Employee();
emp.main();
Here I am importing this class:
class FileHandeling:
def createFile(fo,numOfRecords,data,counterFile):
#Getting the value of counter
frc = open(counterFile,"r");
counter = int(frc.read());
frc.close();
#Taking input and writing to the file
for i in range(counter,numOfRecords+counter):
string = str(i)+data[i];
fo.write(string);
counter += 1;
#Writing back to counter the updated value.
fwc = open(counterFile,"w");
fwc.write(str(counter)+"\n");
fwc.close();
def readFile(fo,searchStr,criteria):
line = fo.readline();
string = [];
while line:
entries = line.split();
if(searchStr == entries[criteria]):
string.append(line);
line = fo.readline();
return string;
def printFile(fo):
fo.seek(0);
lines = fo.readlines();
print "The File: "
for line in lines:
print line;
def updateRecord(fo,fileLoc,updateStr,lineNum):
#Replacing the given record with he updated record and writing back to file
lines = fo.readlines();
fwu = open(fileLoc, "w");
lines[lineNum]= updateStr;
for line in lines:
fwu.write(line);
fwu.close();
def deleteRecord(fo,fileLoc,lineNum):
#Deleting the record
lines = fo.readlines();
fwu = open(fileLoc, "w");
lines.pop(lineNum);
#Correcting the Employee Ids and Writing Back to File
for line in lines:
entry1, entry2, entry3, entry4, entry5 = line.split();
entry1 = str(lines.index(line));
line = entry1+" "+entry2+" "+entry3+" "+entry4+" "+entry5+"\n";
fwu.write(line);
fwu.close();
#Reducing Counter value
frc = open(counterFile,"r");
counter = int(frc.read());
frc.close();
fwc = open(counterFile,"w");
fwc.write(str(counter-1)+"\n");
fwc.close();
In this code I am trying to replicate a database with the help of file but my code gives error saying that 'module' object has no attribute 'createFile'. I also tried creating packages and doing like in java but then it started saying that ImportError: No module named src.fileManipulation. they were just my folders in which I was working and wanted them as packages so I put an __init__.py in them and the tutorials said that this will help in making packages but that didn't happen and since both my files were in same directory I imported it directly but now it gives attribute error and I don't know what that means. Please Help.
I have executed the code in Python default IDLE after correcting some print statements. I am using Python3 so used print (" "). And the result was an endless loop of
Wrong Choice!!!
Press:
1 to enter a new employee
2 to search employee
3 to update employee
4 to delete employee
0 to exit
My kind requtest to you is to revise Python once again.

python: Adding to username

I am fairly new to python and I need to make a program to ask 10 questions, save the score into a file and allow someone to read the scores in from the file.
My problem: I need to check if the person who has done the quiz already has a record in the file, and if so, I need to add their score to the end of their record.
The records should look like this:
name,score,score,score,score,
etc so they can be split using commas.
I am also looking for the simplest answer, not the most efficient. Also, if you could comment the code, it would make it much easier. Here is my code so far:
import random
import math
import operator as op
import sys
import re
def test():
num1 = random.randint(1, 10)
num2 = random.randint(1, num1)
ops = {
'+': op.add,
'-': op.sub,
'*': op.mul,
}
keys = list(ops.keys())
rand_key = random.choice(keys)
operation = ops[rand_key]
correct_result = operation(num1, num2)
print ("What is {} {} {}?".format(num1, rand_key, num2))
while True:
try:
user_answer = int(input("Your answer: "))
except ValueError:
print("Only enter numbers!")
continue
else:
break
if user_answer != correct_result:
print ("Incorrect. The right answer is {}".format(correct_result))
return False
else:
print("Correct!")
return True
print("1. Are you a student?")
print("2. Are you a teacher?")
print("3. Exit")
while True:
try:
status = int(input("Please select an option:"))
except ValueError:
print("Please enter a number!")
else:
if status not in {1,2,3}:
print("Please enter a number in {1,2,3}!")
else:
break
if status == 1:
username=input("What is your name?")
while not re.match("^[A-Za-z ]*$", username) or username=="":
username=input(str("Please enter a valid name (it must not contain numbers or symbols)."))
print ("Hi {}! Wellcome to the Arithmetic quiz...".format(username))
while True:
try:
users_class = int(input("Which class are you in? (1,2 or 3)"))
except ValueError:
print("Please enter a number!")
else:
if users_class not in {1,2,3}:
print("Please enter a number in {1,2,3}!")
else:
break
correct_answers = 0
num_questions = 10
for i in range(num_questions):
if test():
correct_answers +=1
print("{}: You got {}/{} {} correct.".format(username, correct_answers, num_questions,
'question' if (correct_answers==1) else 'questions'))
if users_class == 1:
class1 = open("Class1.txt", "a+")
newRecord = username+ "," + str(correct_answers) + "," + "\n"
class1.write(newRecord)
class1.close()
elif users_class == 2:
class2 = open("Class2.txt", "a+")
newRecord = username+ "," + str(correct_answers) + "," + "\n"
class2.write(newRecord)
class2.close()
elif users_class == 3:
class3 = open("Class3.txt", "a+")
newRecord = username+ "," + str(correct_answers) + "," + "\n"
class3.write(newRecord)
class3.close()
else:
print("Sorry, we can not save your data as the class you entered is not valid.")
EDIT:
Add this function before your "test" function:
def writeUserScore(file, name, score):
with open (file, "r") as myfile:
s = myfile.read()
rows = s.split("\n")
data = {}
for row in rows:
tmp = row.split(",")
if len(tmp) >= 2: data[tmp[0]] = tmp[1:]
if name not in data:
data[name] = []
data[name].append(str(score))
output = ""
for name in data:
output = output + name + "," + ",".join(data[name]) + "\n"
handle = open(file, "w+")
handle.write(output)
handle.close()
After that, where you have "if users_class == 1:" do this:
writeUserScore("Class1.txt", username, str(correct_answers))
Do the same for the other two else ifs.
Let me know what you think!
Try using a dictionary to hold the existing file data.
Read the file in a variable called "str" for example. And then do something like this:
rows = str.split("\n")
data1 = {}
for row in rows:
tmp = row.split(",")
data1[tmp[0]] = tmp[1:]
When you have a new score you should then do:
if username not in data1:
data1[username] = []
data1[username] = str(correct_answers)
And to save the data back to the file:
output = ""
for name in data1:
output = outupt + name + "," + ",".join(data1[name]) | "\n"
And save the contents of "output" to the file.
PS: If you are not bound by the file format you can use a JSON file. I can tell you more about this if you wish.
Hope that helps,
Alex
First, define these functions:
from collections import defaultdict
def read_scores(users_class):
"""
If the score file for users_class does not exist, return an empty
defaultdict(list). If the score file does exist, read it in and return
it as a defaultdict(list). The keys of the dict are the user names,
and the values are lists of ints (the scores for each user)
"""
assert 0 <= users_class <= 3
result = defaultdict(list)
try:
lines =open("Class%d.txt"%users_class,'r').readlines()
except IOError:
return result
for line in lines:
# this line requires python3
user, *scores = line.strip().split(',')
# if you need to use python2, replace the above line
# with these two lines:
# line = line.strip().split(',')
# user, scores = line[0], line[1:]
result[user] = [int(s) for s in scores]
return result
def write_scores(users_class, all_scores):
"""
Write user scores to the appropriate file.
users_class is the class number, all scores is a dict kind of dict
returned by read_scores.
"""
f = open("Class%d.txt"%users_class,'w')
for user, scores in all_scores.items():
f.write("%s,%s\n"%(user, ','.join([str(s) for s in scores])))
def update_user_score(users_class, user_name, new_score):
"""
Update the appropriate score file for users_class.
Append new_score to user_name's existing scores. If the user has
no scores, a new record is created for them.
"""
scores = read_scores(users_class)
scores[user_name].append(new_score)
write_scores(users_class, scores)
Now, in the last portion of your code (where you actually write the scores out) becomes much simpler. Here's an example of writing some scores:
update_user_score(1, 'phil', 7)
update_user_score(1, 'phil', 6)
update_user_score(1, 'alice', 6)
update_user_score(1, 'phil', 9)
there will be two lines in Class1.txt:
phil,7,6,9
alice,6
We read the whole file into a dict (actually a defaultdict(list)),
and overwrite that same file with an updated dict. By using defaultdict(list), we don't have to worry about distinguishing between updating and adding a record.
Note also that we don't need separate if/elif cases to read/write the files. "Scores%d.txt"%users_class gives us the name of the file.

How can I end while loop and skip for loop?

How do I make it where if the user enters 'no' the program won't go through the for loop either. I don't want it to tmpfile.write(line) if the user enters 'no'.
def remove():
coname = raw_input('What company do you want to remove? ') # company name
f = open('codilist.txt')
tmpfile = open('codilist.tmp', 'w')
for line in f:
if coname.upper() in line:
while True:
answer = raw_input('Are you sure you want to remove ' + line.upper() + '?')
if answer == 'yes':
print line.upper() + '...has been removed.'
elif answer == 'no':
break # HERE IS WHERE I NEED HELP
else:
print 'Please choose yes or no.'
else:
tmpfile.write(line)
else:
print 'Company name is not listed.'
f.close()
tmpfile.close()
os.rename('codilist.tmp', 'codilist.txt')
Set a flag variable and then break out of the while loop. Then in the for loop, check if the flag is set, and then break.
PS: if is not a loop
The easiest way to do this is to create a function that gets user input:
def get_yes_or_no(message):
while True:
user_in = raw_input(message).lower()
if user_in in ("yes", "no"):
return user_in
And modify your original function like so:
def remove():
coname = raw_input('What company do you want to remove? ') # company name
f = open('codilist.txt')
tmpfile = open('codilist.tmp', 'w')
for line in f:
if coname.upper() in line:
answer = get_yes_or_no('Are you sure you want to remove ' + line.upper() + '?')
#answer logic goes here
else:
tmpfile.write(line)
else:
print 'Company name is not listed.'
f.close()
tmpfile.close()
os.rename('codilist.tmp', 'codilist.txt')
Python has exceptions, which you can use in place of a GOTO type of construction.
class Breakout(Exception):
pass
def remove():
coname = raw_input('What company do you want to remove? ') # company name
f = open('codilist.txt')
tmpfile = open('codilist.tmp', 'w')
try:
for line in f:
if coname.upper() in line:
while True:
answer = raw_input('Are you sure you want to remove ' + line.upper() + '?')
if answer == 'yes':
print line.upper() + '...has been removed.'
elif answer == 'no':
raise Breakout()
else:
print 'Please choose yes or no.'
else:
tmpfile.write(line)
else:
print 'Company name is not listed.'
except Breakout:
pass
f.close()
tmpfile.close()
os.rename('codilist.tmp', 'codilist.txt')
Notice where in exception is raised in the middle there.
You have to put the whole for loop in a function and use return to get out of it:
def find_and_remove(f,coname,tmpfile):
for line in f:
if coname.upper() in line:
while True:
answer = raw_input('Are you sure you want to remove ' + line.upper() + '?')
if answer == 'yes':
print line.upper() + '...has been removed.'
elif answer == 'no':
return # HERE IS WHERE I NEED HELP
else:
print 'Please choose yes or no.'
else:
tmpfile.write(line)
else:
print 'Company name is not listed.'
def remove():
coname = raw_input('What company do you want to remove? ') # company name
f = open('codilist.txt')
tmpfile = open('codilist.tmp', 'w')
find_and_remove(f,coname,tmpfile)
f.close()
tmpfile.close()
os.rename('codilist.tmp', 'codilist.txt')
Instead of using an infinite loop and breaking when you skip a line, differentiate between the three cases (skip, remove, and invalid answer) using a flag in the loop condition. You set the flag to exit the loop in the skip case, break in the remove case, and leave the flag as-is in the invalid answer case. This lets you use the else clause of the while (which is triggered if the while exits because the condition became false) to detect the skip case. From there, you can jump ahead to the next iteration of the for loop using continue (or skip all the rest of the lines using break - it isn't quite clear from the question which you intend, but the difference is change of keyword):
for line in f:
if coname.upper() in line:
answered = False
while not answered:
answer = raw_input('Are you sure you want to remove ' + line.upper() + '?')
if answer == 'yes':
print line.upper() + '...has been removed.'
break
elif answer == 'no':
answered = True # HERE IS WHERE I NEED HELP
else:
print 'Please choose yes or no.'
else:
continue
else:
tmpfile.write(line)
else:
print 'Company name is not listed.'

Categories