简体   繁体   中英

How to remove <_io.TextIOWrapper name='xyz.txt' mode='w' encoding='UTF-8'> from file?

I am creating a file when running a function for an output that I need to work on, but in addition to the desired output, I get <_io.TextIOWrapper name='xyz.txt' mode='w' encoding='UTF-8'> as output as well in every line of the text file.

Example code:

def stimcount():
with open('results.txt', 'w') as f:
    for rel_node in root.findall("emospan:CharacterRelation",ns):
        if rel_node.attrib['Relation']=="Stimulus":
            source = rel_node.attrib['Governor']
            target = rel_node.attrib['Dependent']
            for span_node in root.findall("emospan:CharacterEmotion",ns):
                if span_node.attrib[my_id]==source:

                    print(span_node.attrib['Emotion'])

                if span_node.attrib[my_id]==target:
                    print(span_node.attrib)
                    print(span_node.attrib, f, file=f)

what should I add to prevent this from happening? I tried adding (..., encoding='utf-8') to the open command, but it had no effect.

Thanks in advance!

The reason for your problem is in this line:

print(span_node.attrib, f, file=f)

The second argument in this call to print (just f ) means that you include a string representation of the file object you're writing to in the output.

Just change this line to:

print(span_node.attrib, file=f)

to solve your problem.

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