【问题标题】:Is there a way to export a print output as a txt. file in python? [duplicate]有没有办法将打印输出导出为 txt。 python中的文件? [复制]
【发布时间】:2020-09-30 15:00:56
【问题描述】:

在玩 Python 时,我想出了一个简单的超市模拟器,我可以在其中对商品及其价格进行分类。

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])

对于输入

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

对于输出

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

我想将打印输出导出为 txt。文件以在另一个项目中使用它。

【问题讨论】:

标签: python python-3.x string


【解决方案1】:

您可以使用以下 sn-p 代码打印到文件而不是标准输出:

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

因此,在您的具体情况下,您可以按如下方式编辑输出循环以打印到文件“out.txt”:

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

【讨论】:

    【解决方案2】:

    根据您希望该程序执行的操作,您可以直接从命令行输出输出(类似于python3 my_program.py &gt; output.txt),也可以从 python 本身打开并写入文件:

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

    【讨论】:

      猜你喜欢
      • 2012-11-27
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      • 2021-02-28
      • 1970-01-01
      • 2021-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多