-1

While playing with Python I came up with a simple simulator for a supermarket where I catalog the items and their prices.

N=int(input("Number of items: "))
n1=0
name1=str(input("Product: "))
price1=float(input("Price: "))
price1="%.2f $" % (price1)
n=n1+1
item1=f"{n}.{name1}---{price1}"
table=[]
table.append(item1)
while n<N:
    name=str(input("Product: "))
    price=float(input("Price: "))
    price="%.2f $" % (price)
    n=n+1
    item=f"{n}.{name}---{price}"
    table.append(item)
for x in range(len(table)):
        print (table[x])

For the input

Number of items: 3
Product: Milk
Price: 5
Product: Water
Price: 1
Product: Apple
Price: 3.49

For the output

1.Milk---5.00 $
2.Water---1.00 $
3.Apple---3.49 $

I want to get the print output exported as a txt. file to use it in another project.

  • 2
    Does this answer your question? [Directing print output to a .txt file](https://stackoverflow.com/questions/36571560/directing-print-output-to-a-txt-file) – Wups Sep 30 '20 at 15:11

2 Answers2

1

You can print to a file instead of the standard output using the following snippet of code:

with open('out.txt', 'w') as f:
    print('Some text', file=f)

So, in your specific case, you could edit the output loop as follows to print to the file 'out.txt':

with open('out.txt', 'w') as f:
    for x in range(len(table)):
        print (table[x], file = f)
morryporry
  • 111
  • 4
0

Depending on what you want this program to do, you could either just pipe the output from the command line (something like python3 my_program.py > output.txt) or open and write the file from python itself:

with open("output.txt", "w") as outfile:
    for x in range(len(table)):
        outfile.write(table[x] + "\n")
frollo
  • 1,296
  • 1
  • 13
  • 29