Home > Mobile >  Can you tell me what's wrong with this loop?
Can you tell me what's wrong with this loop?

Time:10-07

I have this code:

import sys

cities = 'me, myself, eye'

company_types = 'WHAT, WHO'

with open("result.txt", 'w') as fid:
    for city in cities:
        for company_type in company_types:
            fid.write(company_type.strip()   " in "   city.strip())
            fid.write("\r\n")

I get this output:

<built-in method write of _io.TextIOWrapper object at 0x0000019E4C3017D0>

What is wrong with the code? How do I fix it?

CodePudding user response:

Please convert cities and company_types to lists or any iterable type.

cities = ['me', 'myself', 'eye']

company_types = ['WHAT', 'WHO']

with open("/full/path/to/file/result.txt", 'w') as fid:
    for city in cities:
        for company_type in company_types:
            fid.write(company_type.strip()   " in "   city.strip())
            fid.write("\r\n")

Try to use full paths to ensure that file is created in exact place you wanted, instead of Python current path.

CodePudding user response:

import sys

#you are defining a string instead of a list, Try this.
cities = ['me', 'myself', 'eye']
company_types = ['WHAT', 'WHO']

with open("result.txt", 'w') as fid:
    for city in cities:
        for company_type in company_types:
            fid.write(company_type.strip()   " in "   city.strip())
            fid.write("\r\n")

CodePudding user response:

Code is ok, I've just check it. But check you file, may be it is already presend and need to set access to it. Or use full path to file. For example, if I need make new file near my script I use:

os.path.join(os.path.dirname(os.path.realpath(__file__)), "result.txt")
  • Related