2013-12-20 43 views
0

我试图用文件内的已知字符串重命名一个文件。 我可以从搜索文件的输出中得到我想要的信息。如果它有额外的回车,我无法获得我所掌握的信息。这里是代码:查找文件中的字符串

>>> with open('c:/test/277coreB.txt', 'r') as config: 
...  for line in config: 
...   if "hostname" in line: 
...      host = line 
...  #This is where the extra carriage return come from and I cannot get rid of it 
>>> print host[9:] 
XR77-2-DC-Core-B 

回答

3

str.rstrip('\n')将摆脱尾随的换行符。

+0

太快了,我很感激帮助。那是修复。 – Marc

+2

你也可以使用'host = line.strip()',它会在'line'的开头和结尾去掉所有的空白符(包括换行符)。 –