2014-03-06 49 views
0

我试图从函数中创建的列表中删除\n。我的代码去除它似乎没有工作。我没有得到一个错误?删除换行符不起作用

CODE

#!/usr/bin/python 

""" 
Description: 

Basic Domain bruteforcer 

Usage: 
    your_script.py (-f <file>) (-d <domain>) [-t 10] [-v] 
    your_script.py -h | --help 

Arguments: 
    -f --file File to read potential Sub-domains from. (Required) 
    -d --domain Domain to bruteforce. (Required) 
Options: 
    -h --help  Show this screen. 
    -p --proxy Proxy address and port. [default: http://127.0.0.1:8080] (Optional) 
    -t --thread Thread count. (Optional) 
    -v --verbose Turn debug on. (Optional) 
""" 
from docopt import docopt 


def fread(dwords, *args): 
     flist = open(dwords).readlines() 
     #print current list 
     print flist 
     nlist = flist 
     for i in nlist: 
      i.rstrip('\n') 
      return nlist 

if __name__ == "__main__": 
     arguments = docopt(__doc__, version='0.1a') 
     # print new list with removed \n 
     print fread(arguments['--file']) 

回答

8

字符串是不可变的,i.rstrip('\n')回报一个新的字符串。

使用列表理解:

def fread(dwords): 
    flist = open(dwords).readlines() 
    return [s.rstrip('\n') for s in flist] 

,或者因为你正在阅读的整个文件到内存反正str.splitlines()

def fread(dwords): 
    return open(dwords).read().splitlines() 
在您看来@Martijn皮特斯
+0

我现在不读入内存?这是更好的做法? – iNoob

+0

@LearningCode:你可以直接在文件对象上循环,这会给你个别的行。 –

+0

@LearningCode:例如,打开(dwords)作为fobj:','用于fobj中的行:','print fobj.rstrip('\ n')'。 –