I have a text file that is called paintingJobs.txt, each line is structured in this way:
Estimate Number, Estimate Date, Customer ID, Final Total, Status (E for Estimate, A for Accepted job or N for Not accepted), and Amount Paid.
Here is an extract:
E5341, 21/09/2015, C102, 440, E, 0
E5342, 21/09/2015, C103, 290, A, 290
E5343, 21/09/2015, C104, 730, N, 0
I would like the user to input any Estimate number and for that line to be outputted. How can I achieve this?
Here is what I came up with but it doesn't work as required:
def option_A():
es_num = str.upper (input ("Please enter the estimate number: "))
with open('paintingJobs.txt', 'r') as file:
line = file.readline ()
print (line, end = '')
if es_num in file:
#print whole line
else:
print("Not found")
I would like to display the information in this format
Estimate Number: the estimate number
Customer ID: the customer ID
Estimate Amount: the final total
Estimate Date: the estimate date
Status: the status
To print the line, I suggest you to simply iterate on each line of the file as follows:
def option_A():
es_num = str.upper (input ("Please enter the estimate number: "))
result = "Not found"
with open('paintingJobs.txt', 'r') as file:
for line in file:
if es_num in line:
result = line
break
print(result)
To format the display, you can split the line with comma as separator to get a list of information. Then format your display, as follows:
data = result.split(',')
print("Estimated number:{0}".format(data[0]))
print("Customer ID:{0}".format(data[2]))
...etc...
Then if you need some data which are more complex to retrieve from the text file, the powerful way is to use regex with for instance the method re.match(...).
Related
I have a problem with \n when I am trying to write a datestring and number values in txt file
pattern = [ ...
'Date %s - First %d \n', ...
'Date %s - Second %d \n' ...
'%d, \n', ...
'*ENDDO\n\n'];
t = datetime('now');
[fid, msg] = fopen('date_and_values.txt', 'wt');
assert(fid ~= -1, 'Cannot open file %s: %s', 'долбоеб.txt', msg);
formatOut='dd.mm.yy';
dateString = datestr(t);
disp(dateString);
formatNumb = '\t%d';
res = [dateString num2str(1,formatNumb) num2str(2,formatNumb)];
for k = 1:17
fprintf(fid, pattern, res);
% % Perhaps this is faster:
% % fwrite(fid, strrep(pattern, '%d', sprintf('%d', k)), 'char');
end
fclose(fid);
I want the data looks like this:
But instead I get data in file look like this:
What am I doing wrong?
Change pattern to
pattern = ['Date %1$s - First %2$d \n', ...
'Date %1$s - Second %3$d \n\n'];
and use
fprintf(fid, pattern, dateString, num2str(1,formatNumb), num2str(2,formatNumb));
instead, you will get the desired output.
Note the use of identifiers in the above. (ctrl+F "identifiers" in documentation.) Without identifiers, each time you have a new formatting operator, a new input is expected by fprintf(). On top of that, every uniquely identified operator in your pattern should correspond to 1 input in fprintf().
(The pattern in OP also contains some superfluous trailing bits that are not found in the example output.)
I don't know if I understand what you are looking for, but, have you tried this?
res = [dateString num2str(1,formatNumb) num2str(2,formatNumb) '\n'];
I have a json file with 6 "coins" to each user (which the user can change), I am trying to get this data saved in the json file and match it with another 6 coin pattern in order to check how many matches are made in total. The json file format is:
{"331971067788787733": [":Helicopter:", ":Skateboard1:", ":swords:", ":mace:", ":Helicopter:", ":Skateboard1:"]}
With each "coin" being a discord emoji.
The code for the user to save it is:
#client.command()
async def Shibaku1(ctx, coin1, coin2, coin3, coin4, coin5, coin6):
with open('Shibaku1.json', 'r') as f:
coins_data = json.load(f)
coins_data[str(ctx.author.id)] = (coin1, coin2, coin3, coin4, coin5, coin6)
with open('Shibaku1.json', 'w') as f:
json.dump(coins_data, f)
How do I extract the string value of each coin from the json file with the users 6 coins? in order to compare them with the main pattern to find the number of matches.
So u can use for loop i list to compare the values, example given below :
for coin in coins_data[str(ctx.author.id)]:
if coin != new_coin:
#do smthing
I am trying to be able to have a person specify how many sets of dice they want to roll. at present if they want to roll three sets of a d100 they have to enter the command 3 times. I want to be able to have them enter an amount like !3d100 and have it roll it 3 times?
#client.command(name='d100', help='Rolls a d100 sice')
async def dice(context):
diceEmbed = discord.Embed(title="Rolling for " + str(context.message.author.display_name), color=0xCC5500)
roll = (random.randint(1, 100))
url = "http://157.230.225.61/images/dice/d100/d100_{:03}.png"
url = url.format(roll)
diceEmbed.set_image(url=url)
diceEmbed.add_field(name="d100", value=roll, inline=True)
if roll == 1:
diceEmbed.set_footer(text="FUMBLE")
await context.message.channel.send(embed=diceEmbed)
First of all consider using f string. You will have to add a input to your command !dice 3 This will give you 3 rolls if no amount given only 1.
Keep in mind in embed you can only place one image so i took the highest according to you.
#bot.command()
async def dice(ctx, amount: int = 1):
diceEmbed = discord.Embed(title=f"Rolling for {ctx.message.author.display_name}", color=0xCC5500)
max_roll = 0
for i in range(amount):
roll = (random.randint(1, 100))
if roll > max_roll:
url = f"http://157.230.225.61/images/dice/d100/d100_{roll:03d}.png"
max_roll = roll
diceEmbed.add_field(
name=f"Role number {i+1}", value=roll, inline=False)
if roll == 1:
diceEmbed.set_footer(text="FUMBLE")
# You can have only one image which is the highest
diceEmbed.set_image(url=url)
await ctx.message.channel.send(embed=diceEmbed)
I'm using a text file with lines of movies. If a user inputs Oz, I want to output all the movies in the file that have the word Oz in it.
This is what I have so far.
puts "Enter the keyword you want to search for: "
keyword = gets
movies_file = File.new("movies.txt", "r")
movies = movies_file.read
movies_list = movies.split(" ")
match_list = []
movies_list.each do |w|
matchObj = w.match(keyword)
if matchObj then
matchlist.push(matchObj.captures[0])
end
end
match_list.each do |title|
puts title
end
Presuming you've got the file organized like this:
Wizard of Oz
Battlefield Earth
Twilight
Ozymandias
Then you can read it in this way:
lines = File.readlines('movies.txt').map(&:chomp)
Then to find matching lines:
matches = lines.grep(phrase)
There's no need for all the each stuff. Also the then on an if is almost never put in there, it's just useless decoration.
Python 3 program allows people to choose from list of employee names.
Data held on text file look like this: ('larry', 3, 100)
(being the persons name, weeks worked and payment)
I need a way to assign each part of the text file to a new variable,
so that the user can enter a new amount of weeks and the program calculates the new payment.
Below is my code and attempt at figuring it out.
import os
choices = [f for f in os.listdir(os.curdir) if f.endswith(".txt")]
print (choices)
emp_choice = input("choose an employee:")
file = open(emp_choice + ".txt")
data = file.readlines()
name = data[0]
weeks_worked = data[1]
weekly_payment= data[2]
new_weeks = int(input ("Enter new number of weeks"))
new_payment = new_weeks * weekly_payment
print (name + "will now be paid" + str(new_payment))
currently you are assigning the first three lines form the file to name, weeks_worked and weekly_payment. but what you want (i think) is to separate a single line, formatted as ('larry', 3, 100) (does each file have only one line?).
so you probably want code like:
from re import compile
# your code to choose file
line_format = compile(r"\s*\(\s*'([^']*)'\s*,\s*(\d+)\s*,\s*(\d+)\s*\)")
file = open(emp_choice + ".txt")
line = file.readline() # read the first line only
match = line_format.match(line)
if match:
name, weeks_worked, weekly_payment = match.groups()
else:
raise Exception('Could not match %s' % line)
# your code to update information
the regular expression looks complicated, but is really quite simple:
\(...\) matches the parentheses in the line
\s* matches optional spaces (it's not clear to me if you have spaces or not
in various places between words, so this matches just in case)
\d+ matches a number (1 or more digits)
[^']* matches anything except a quote (so matches the name)
(...) (without the \ backslashes) indicates a group that you want to read
afterwards by calling .groups()
and these are built from simpler parts (like * and + and \d) which are described at http://docs.python.org/2/library/re.html
if you want to repeat this for many lines, you probably want something like:
name, weeks_worked, weekly_payment = [], [], []
for line in file.readlines():
match = line_format.match(line)
if match:
name.append(match.group(1))
weeks_worked.append(match.group(2))
weekly_payment.append(match.group(3))
else:
raise ...