首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将Python输出打印为.txt文件

将Python输出打印为.txt文件
EN

Stack Overflow用户
提问于 2019-10-04 17:24:22
回答 2查看 91关注 0票数 0

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

我希望将代码的结果打印到一个.txt文件中,然后我可以使用打印的数字作为变量,从.txt文件的顶部开始读取多少行,并将该文本分隔到它自己的.txt文件中。

我已经附加了一个链接到一个小图来解释这个更好的1

我已经研究了一段时间,但似乎找不到它!有谁有办法做到这一点吗?

我的代码如下:

代码语言:javascript
复制
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)
EN

回答 2

Stack Overflow用户

发布于 2019-10-04 17:28:12

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

使用stdout将是危险的,并且可能会影响您没有考虑到的部分代码-我建议完全删除您的代码部分。

票数 0
EN

Stack Overflow用户

发布于 2019-10-04 18:01:24

您还可以使用>运算符

python trial.py > trial.txt

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58233519

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档