将Python输出打印到.txt文件

时间:2019-10-04 09:24:21

标签: python

尝试将代码输出打印到.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)

2 个答案:

答案 0 :(得分:0)

您将使用<filename>.write而不是print

使用标准输出会很危险,并且可能会影响您未考虑的部分代码-我建议完全删除部分代码。

答案 1 :(得分:0)

您还可以使用>运算符

python trial.py > trial.txt