[英]Outputting to a text file
如何將以下代碼打印到.txt文件
y = '10.1.1.' # /24 network,
for x in range(255):
x += 1
print y + str(x) # not happy that it's in string, but how to print it into a.txt
有復制粘貼,但寧願嘗試更有趣的東西。
f = open('myfile.txt', 'w')
for x in range(255):
ip = "10.1.1.%s\n" % str(x)
f.write(ip)
f.close()
scriptname.py >> output.txt
什么是x += 1
? 它似乎是range(255)
基於0的變通方法 - 它給出了序列0,1,2 ... 254。
range(1,256)
將更好地給你你想要的。
其他答案的替代方案:
NETWORK = '10.1.1'
f = open('outfile.txt', 'w')
try:
for machine in range(1,256):
print >> f, "%s.%s" % (NETWORK, machine)
finally:
f.close()
在Python 3中,您可以使用print函數的關鍵字參數file。 “a”表示“追加”。
f = open("network.txt", "a")
for i in range(1, 256):
print("10.1.1." + str(i), file=f)
f.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.