Search code examples
pythonfilenameerror

NameError: name 'write' is not defined when writing into file


Trying to write something into a file but getting

NameError: name 'write' is not defined

Error when I try to write. I tried both codes and they gave out the same error

What am I doing wrong?

with open("/etc/tor/torrc", "a") as myfile:
    myfile.write("""
    VirtualAddrNetwork 10.192.0.0/10
    AutomapHostsOnResolve 1
    ransPort 9040    
    DNSPort 53""")

file = open("/etc/tor/torrc","a")
file = write("""
    VirtualAddrNetwork 10.192.0.0/10
    AutomapHostsOnResolve 1
    TransPort 9040
    DNSPort 53""")

Solution

  • The first way is correct. The second way should look like this:

    file = open("/etc/tor/torrc","a")
    file.write("""
    VirtualAddrNetwork 10.192.0.0/10
    AutomapHostsOnResolve 1
    TransPort 9040
    DNSPort 53""")
    

    write is a member method of a file object, so it should be used like this: file.write(string)