Hi,

I want to read a line in the file and check the content in the line, for example if the line starts with the text "sample test ..." i want to check wether the line starts with sample, but my code always return no result even thou the file contains "sample test ..."

code:
import os
import string

root = "\home\sathappan"
inputfile = os.path.join(root,"data.txt")
outputfile = os.path.join(root,"dataexp.bat")
a = open(inputfile)
b = open(outputfile,"a")
while 1:
line = a.readline().strip()
if line == 'Sample*':
print line
b.write(line)
a.close()
b.close()

data.txt

example 123
test test
sample text
sampe test line
text line
ex test

I think the problem is when you test the line to see if the word sample is in the line. In this case your code is asking if the line that you just read in consists of sample* and nothing else.

Instead, read in your line and use line.find('sample'). This function will return the offset in the line where it encounters the word sample. So if the word sample is at the beginning of the line it will return zero. If the function returns -1 then it was not found

line = a.readline().strip()
if line.find('sample') == 0:
    print line
    b.write(line)

thanks alot kthompson...


data.txt

YES 2.6
NO 1.3
YES 5.8
NO 5.6
NO 8.9
NO 0.8
YES 6.7
YES 6.5
NO 8.2
Update 6.12
YES 8.2
NO 4.0
YES 9.0
NO 3.3
Update 6.13
NO 4.5

Ignore any line containing "Update"
Output the number of yes's and output the total number of lines containing either yes or no


if line.find('Update') == 0:
break
elif line.find('YES') == 0:
print line
b.write(line '\n')
elif line.fine('NO') == 0:
print line
b.write(line '\n')


Return the error:

File "pars.py", line 12
elif line.find('YES') == 0:
^
SyntaxError: invalid syntax

Can anyone help me!!!


Thnxxx in advance

From what i can see your code is not indented properly, so that could be because you are not using code tags when posting which means that indentation is normally lost.

CODE HERE

tags (without the space after the end one)
They mean that it is a lot easier to tell what is wrong.

Are you indenting your code properly? In the code snippet at the bottom you don't have the code blocks that come after your ifs and elifs indented. I don't know if you just didn't indent on the forum, or if your file is like that. Also, could you please use code blocks so that your code is easier to read?

This seems to work for me. Note that you have a typo on one of your lines that I fixed in my example

if line.find('Update') == 0:
    break
elif line.find('YES') == 0:
    print line
    b.write(line '\n')
elif line.find('NO') == 0: #The typo is here, you had line.fine instead of find.
    print line
    b.write(line '\n')

I hate it when I post something and someone else is posting pretty much the same thing at the same time and I end up looking like a dumbass who just repeats what was said above me.

import os
root = "/home/sathappan/mydoc"
inputfile = os.path.join(root,"data.txt")
outputfile = os.path.join(root,"dataexp.bat")
a = open(inputfile)
b = open(outputfile,"a")
YES=0
NO=0
while 1:
line = a.readline().strip()
if line.find('YES') == 0:
print line
b.write(line +'\n')
YES += 1
elif line.find('NO') == 0:
print line
b.write(line +'\n')
NO += 1
else:
continue
print (YES)
Print (NO)
a.close()
b.close()

Error:

File "ds.py", line 14
YES += 1
^
SyntaxError: invalid syntax

Really thanx alot for your valid points and help.. I am newbie.. why i am not able to increment a value of Yes here???

It could be an indentation problem, but since you don't wrap your code in code tags as paulthom says above, it's difficult to see what's wrong.

It could be an indentation problem, but since you don't wrap your code in code tags as paulthom says above, it's difficult to see what's wrong.

import os
root = "/home/sathappan/mydoc"
inputfile = os.path.join(root,"data.txt")
outputfile = os.path.join(root,"dataexp.bat")
a = open(inputfile)
b = open(outputfile,"a")
YES=0
NO=0
while 1:
        line = a.readline().strip()
        if line.find('YES') == 0:
              print line
              b.write(line +'\n')
                YES += 1
        elif line.find('NO') == 0:
              print line
              b.write(line +'\n')
                NO += 1
        else:
                continue
print (YES)
Print (NO)
a.close()
b.close()

[Error]
line 14
YES += 1
^
SyntaxError: invalid syntax
[/Error]

hope this time it prints with the proper indentation///

The line YES += 1 should have the same indentation as the line b.write(line +'\n') above. Same remark for the line NO += 1 . Also I don't know how you indent your code, but use only space characters, not tab characters.

The line YES += 1 should have the same indentation as the line b.write(line +'\n') above. Same remark for the line NO += 1 . Also I don't know how you indent your code, but use only space characters, not tab characters.

import os
root = "/home/sathappan/mydoc"
inputfile = os.path.join(root,"data.txt")
outputfile = os.path.join(root,"dataexp.bat")
a = open(inputfile)
b = open(outputfile,"a")
YES = 0
NO = 0
while 1:
        line = a.readline().strip()
        if line.find('YES') == 0:
                print line
                b.write(line +'\n')
                YES = YES + 1
        elif line.find('NO') == 0:
                print line
                b.write(line +'\n')
                NO = NO + 1
        else:
                continue
print (YES)
print (NO)
a.close()
b.close()

I use tabs for indentation. My program does not end at all. Also it does not print the value of YES and NO variable. I have to press Ctrl + C to quit the prgm. Any idea???

[OUTPUT]
python ds.py
YES 2.6
NO 1.3
YES 5.8
NO 5.6
NO 8.9
NO 0.8
YES 6.7
YES 6.5
NO 8.2
YES 8.2
NO 4.0
YES 9.0
NO 3.3
NO 4.5
Traceback (most recent call last):
File "ds.py", line 11, in ?
if line.find('YES') == 0:
KeyboardInterrupt
[/OUTPUT]

Your loop while 1 runs forever. You must exit the loop when a.readline() returns an empty line (the string "" ). This test must be done before you call the method strip() . You can exit the loop with a break statement.

yes that works... gr8.. thx aton... can you tell me how to replace text for example: while writing line in the newfile, i want to substitute yesplease for yes.

line = a.readline().strip()
        if line.find('YES') == 0:
                l=str(line.split(' '))
                print line
#               print l
                b.write('Yesplease'+l + '\n')
                Y = Y + 1
        elif line.find('NO') == 0:
                N = N + 1
        elif line == "":
                break
        else:
                continue

[OUTPUT]
[sathappan@santhosh mydoc]$ python cc.py
YES 2.6
YES 5.8
YES 6.7
YES 6.5
YES 8.2
YES 9.0
Total Number of Lines with YES
6
[sathappan@santhosh mydoc]$
[sathappan@santhosh mydoc]$
[sathappan@santhosh mydoc]$ cat dataexp.bat
Yesplease
Yesplease
Yesplease
Yesplease
Yesplease
Yesplease
[sathappan@santhosh mydoc]$ vim cc.py
[sathappan@santhosh mydoc]$
[/OUTPUT]


My question is I am not able to use the string
if i make my line no: 15 as b.write('Yesplease'+l(0) + '\n')
i get the error
Traceback (most recent call last):
File "cc.py", line 15, in ?
b.write('Yesplease'+l(0) + '\n')
TypeError: 'str' object is not callable


Any idea... I want to use the 1st or the 2nd argument alone.

You cant go () after a string. i think you mean to use the [] signs. These allow you to select certain parts of a string so you would have:

b.write('yesplease'+l[0]+'\n')

even b.write('yesplease'+l[0]+'\n') gives the 1st character in the line and not the 1st argument itslef. is there any way to get the 1st argument itself???


Thanxxxx

The first argument? Do you mean the first word in the string? If you want to get the first word in the string you might try doing some string slicing. There are tutorials out there that you can follow, but this is how I think it would go...

sentence = 'the quick brown fox.'
print sentence[0:sentence.find(' ')]

# This code prints the word 'the'

You already know that when you have a string you can use brackets [] to pick out a single letter in the string. If you put two numbers in the brackets, separated by a colon then you can pick out a range of letters. For example yourstring[0:4] will give you the first four characters in your string. In my example above, I have started with the first character of my string (0), added a colon to indicate a range of characters. But instead of specifying a second character, I used the find function to get the location of the first space. sentence.find(' ') will return 3, so I have effectively written sentence[0:3]

Another way that you could get the first word is to split the string into a list of words. This is particularly helpful if you needed to get the first two words out of the string. That would be more difficult with the code I wrote above, but is really easy with this code...

sentence = 'the quick brown fox jumped over the lazy dog.'
listofwords = sentence.split()
print listofwords[0]
# output> the
print listofwords[0] + ' ' + listofwords[1]
# output> the quick
print listofwords[0], listofwords[1]
#output> the quick.  Same as last command but done with commas instead of adding a space.

Another way that you could get the first word is to split the string into a list of words. This is particularly helpful if you needed to get the first two words out of the string. That would be more difficult with the code I wrote above, but is really easy with this code...

sentence = 'the quick brown fox jumped over the lazy dog.'
listofwords = sentence.split()
print listofwords[0]
# output> the
print listofwords[0] + ' ' + listofwords[1]
# output> the quick
print listofwords[0], listofwords[1]
#output> the quick.  Same as last command but done with commas instead of adding a space.

Thank you.. I am clear now.. and it works for me tooooo...

My hearty thanx to all who helped me in this...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.