简体   繁体   中英

return file object from generator python

I'm using the following to read a file and let me edit a line inside the file

haystack = open('myxml.xml') 

def needlefinder(file):
    for line in file:
        if 'MyTag' in line:
            line = line.replace('alt="1"','alt="0"')
            #print line

    needle = needlefinder(haystack)
    print needle

Im wondering how can I return the file as a string? I want to basically edit this line on the fly and return the whole edited document.

Just place all the lines in a list (of string ), and return it at the end of your function, like that:

def needlefinder(file_):
    lines = list()
    for line in file_:
        if 'MyTag' in line:
            line = line.replace('alt="1"','alt="0"')
        lines.append(line)
    return lines

haystack = open('myxml.xml')
needle = needlefinder(haystack)
print needle

如果您询问如何以字符串形式返回任何内容,请添加str()

return(str())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM