0

I've problem in the comparison line line == a[1] because it doesn't go to this loop. I tried testing the output and found that there is value 'a' in the file already. Below is my code.

a = "djsajdlasak"
f = open('users.txt','r+')
k = 0
for line in f:
    print line
    if line == a:
        k = 1
if k == 0:
    f.write(a + '\n')
f.close()
jade
  • 29
  • 4
  • Please explain exactly (1) what you're trying to do (2) what's the expected output (3) what's the current output or error messsage – shx2 Oct 03 '14 at 05:39

2 Answers2

0

for line in f yields lines together with line terminators, so you need to strip them, see to read line from file in python without getting "\n" appended at the end

Community
  • 1
  • 1
wRAR
  • 25,009
  • 4
  • 84
  • 97
0

You need to strip out the newline/line terminator from the lines you are reading from the file. You can use str.strip, to achieve what you would would desire.

either change the line for line in f: for line in(elem.strip() for elem in f): or add an extra line following your for statement

for line in f:
    line = line.strip()
    print line
    if line == a:
        k = 1
Abhijit
  • 62,056
  • 18
  • 131
  • 204