2017-09-24 51 views
1

我使用以下代码逐行读取带有主机地址的txt文件,但是当代码创建并写入文件作为日志时,它会用引号和'?'写入文件。性格:写入文件时不使用引号

的代码是这样的:

import getpass 
import sys 
import telnetlib 

user = "cisco" 
password = "cisco" 

file = open('hosts.txt', 'r') 
for line in file: 

     tn = telnetlib.Telnet(line) 

     tn.read_until("Username: ") 
     tn.write(user + "\n") 
     tn.read_until("Password: ") 
     tn.write(password + "\n") 
     tn.write("enable \n") 
     tn.write(password + "\n") 

     tn.write("sh ver | i revision \n") 
     tn.write("exit \n") 

     str_all = tn.read_all() 
     log = open(line + ".txt","w") 
     log.write(str_all) 
     tn.close() 

所以创建的文件是这样的:

[[email protected] Projeto]$ ls 
21.10.176.4?.txt clean_up_819 hosts.txt master.py test1.txt teste.txt 

后来,当我使用文件与问号displaing:

[[email protected] Projeto_QoS]$ cat '21.10.176.4 
.txt' 

有什么办法可以保存在一个标准化的文件中只有21.10.176.4.txt

回答

0

您的文件名没有引号;那些被你的shell的tab-completion添加来保护所具有的换行符。

换行符来自line,它可以检测到最后一行是否有一行(并且为了方便重写类似文件)。见How can I remove (chomp) a newline in Python?