#๐Ÿ”’ New to python and i need help understanding file editing

46 messages ยท Page 1 of 1 (latest)

karmic valley
#

So im trying to write a program that takes information from a text file of grocery store items, their price, any potential discounts, and if they are taxed or not, then doing the math for each item and outputting it to a new file. The problem im having (besides being in way over my head) is how to link each section of the first file in the code and outputting line by line the information i need to give in the 2nd. I keep looking up similar code and everyone does it differently. But when i try i cant get it to work.

upper sluiceBOT
#

@karmic valley

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

karmic valley
#

honestly ive scrapped most of them and restarted each time because i feel like im doing it wrong. I honestly dont even know where to start anymore

safe apex
#

start by figuring out how you want to format your data in a file

karmic valley
#

it should look something like this when im done

#

this is what the first file looks like

safe apex
#

sure. first thing i'd do is write a function that parses that information into a data structure

karmic valley
#

would that be for line in infile?

safe apex
#

yes, you need to iterate over each line, and split by spaces

#

you'd also need to normalize each value. for instance, turn the string "$2.99" into a float with value 2.99, and turn a discount value of "10%" into the float value 0.1, a tax value of "N" into a boolean False

karmic valley
#

for line in infile:
try:
item, price, discount, tax = line.strip().split(',')

#

would that be first then?

safe apex
#

you need to split by spaces

#

line.split() is fine

karmic valley
#

ah

#

for line in infile:
try:
item, price, discount, tax = line.split()

#

then would i strip $ from each line?

safe apex
#

you'd only strip it from the price variable

#

float(price[1:]) should be fine

karmic valley
#

do i need to write that in the same line or below it?

safe apex
#

where do you think it should go?

karmic valley
#

in the line under try? so it would be:
for line in infile:
try:
item, float(price[1:]), discount, tax = line.split()

safe apex
#

hm

#

how much previous python experience do you have

karmic valley
#

almost none i started about 2 months ago

safe apex
#

you need to go through a basic tutorial first

#

you seem to be having trouble with just syntax

karmic valley
#

im just very frusterated because files are new and im not sure what im doing

#

i havnt had anyone teach me its all been trying to learn in spare time

safe apex
#

otherwise this will be very frustrating without me just giving you the code

karmic valley
#

thats fair

#

ive done other projects im just new to file editing

#

any suggestions on where to go?

safe apex
upper sluiceBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

storm charm
# karmic valley ive done other projects im just new to file editing

And bear in mind that if this is entirely your project, you get to make up your own data file format.

When you say "it should look something like this", is that how you want to display the information, or also how you want it stored. It seems to me that your task would be well suited to a CSV (comma separated value) file, which is a text file of lines, where each line is a row of your data eg 1 line er grocery item, with the values separated by commas:

item,price,discount
apple,1.00,0
pear,2.00,1

Obviously that's not looking like your nice table, but it is easy to read into your programme, then your programme can print a nice table for display purposes.

There's a presupplied csv module for reading and writing CSV files.

The other big thing with text files is: when you "edit" them you basicly have to read the whole thing in, make whatever changes, then write the whole thing back out.

karmic valley
#

is there an easy way to post code here or should i just use screenshots?

upper sluiceBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

karmic valley
#
def math(filename="items1.txt"):
    tax_rate = 0.13
    try:
        with open('items1.txt', 'r') as infile, open('items2.txt', 'w') as outfile:
            header = print(f"{'Item Name':<20}{'Actual Price':<20}{'Tax':<20}{'Total Cost':<20}")
            for line in infile:
                try:
                    name, price, discount, tax = line.split()
                    price = float(price[1:])
                    if discount.isalpha():
                        discount = 0
                    else:
                        discount = float(discount[:1])*0.01
                    cost = price * (1-discount)
                    if tax.upper() == 'Y':
                        tax = cost * tax_rate
                    else:
                        tax = 0.0
                    total_cost = cost + tax
                    print(f"{name:<20}${cost:<20.2f}${tax:<20.2f}${total_cost:<20.2f}")
                except ValueError as e:
                    print(f"Error processing line: {line.strip()} - {e}")
    except FileNotFoundError:
        print(f"Error: The file {filename} was not found.")
math()

this is what ive been able to put together so far but im not sure how to ignore the first line of the text file so i dont read that line as an error and also some of the math seems to not be working?

#

this is my output

upper sluiceBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.