2013-12-20 44 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'的開頭和結尾去掉所有的空白符(包括換行符)。 –