首页 > 解决方案 > 将 Python 输出打印到 .txt 文件

问题描述

我在尝试将我的代码输出打印到 .txt 文件时遇到了一些问题。

我希望将代码的结果打印到 .txt 文件中,然后我可以将打印的数字用作从 .txt 文件顶部读取多少行的变量,将那段文本分成自己的 .txt 文件。

我附上了一个小图的链接,以更好地解释这一点1

我已经研究了一段时间,似乎无法找到它!有人对如何做到这一点有任何想法吗?

我的代码如下:

from itertools import permutations
import string


# Enter new brand names to following lists

brand_names = "8x8, AmazonAWS, Checkpoint, Cisco, Citrix, Commvault, Dell, Dell_EMC, Google, Google_Cloud, HPE, Hyland, IBM, IBM_Cloud, Microsoft, Microsoft_Azure, NetApp, Oracle, Pure_Storage, SAP, Thompson_Reuters, Veritas, VMware, Aerohive, Aramark, Bloomberg, BMC, Box, CompuCom, Cybera, Extreme, FireEye, GE, Globoforce, GPSI, Infor, Lux_Research, MetTel, Oracle_Cloud, PAR_Invista, Puppet, Rackspace, Ruckus, Salesforce, SonicWall, SPI, Splunk, Stratix, Supermicro, Tenable, Ultipro, US_Bank, Veeam, VIP"

for group in permutations(['8x8', 'AmazonAWS', 'Checkpoint', 'Cisco', 'Citrix', 'Commvault', 'Dell', 'Dell_EMC', 'Google', 'Google_Cloud', 'HPE', 'Hyland', 'IBM', 'IBM_Cloud', 'Microsoft', 'Microsoft_Azure', 'NetApp', 'Oracle', 'Pure_Storage', 'SAP', 'Thompson_Reuters', 'Veritas', 'VMware', 'Aerohive', 'Aramark', 'Bloomberg', 'BMC', 'Box', 'CompuCom', 'Cybera', 'Extreme', 'FireEye', 'GE', 'Globoforce', 'GPSI', 'Infor', 'Lux Research', 'MetTel', 'Oracle_Cloud', 'PAR_Invista', 'Puppet', 'Rackspace', 'Ruckus', 'Salesforce', 'SonicWall', 'SPI', 'Splunk', 'Stratix', 'Supermicro', 'Tenable', 'Ultipro', 'US Bank', 'Veeam', 'VIP'], 3):
    print('_'.join(group)) 
print
print

# Python3 code to demonstrate 
# to count words in string 
# using regex (findall()) 
import re 


# printing original string 
print ("The original string is : ")
print
print("'" + brand_names + "'") 


# using regex (findall()) 
# to count words in string 
res = len(re.findall(r'\w+', brand_names)) 

print
print
print

# printing result 
print ("The number of brands are : " + str(res)) 

print
print
N = res
import sys
sys.stdout = open("file.txt", "w+")
print (group)

标签: python

解决方案


您也可以使用>运算符

python trial.py > trial.txt


推荐阅读