M. Rox M. Rox - 6 months ago 16
Python Question

Doesn't write to file [Python]

I am trying to make a string write in a text file, but only if that string is already not in the text file.

b = raw_input("IP Adress: ")
if(b == '0'):
a = 0
c = raw_input("Player Name: ")
if(c == '0'):
a = 0
if(a != 0):
line = "Text\IPs\{}.txt".format(b)
output_filee = open(line, 'w+')
output_file = open(line, 'r')
lines = output_file.readlines()
for line in lines:
if(line != c):
found = 1
if(found == 1):
print '"{}" has been added to the IP Address {}'.format(c,b)

The code above makes the new file in the folder, but with nothing in it.
Any suggestions?


The logic in your for loop is wrong. It's not checking whether the string is missing from the file, it's checking whether there's some line in the file that doesn't match the string. If the file is empty, the loop won't do anything, so it never sets found = 1.

You need to invert the logic. Change it to:

found = False
for line in lines:
    if line == c:
        found = True
if not found: