+ 1

Checking file objects

How I can check a specific object(like a number) is existing in my file ???

11th May 2020, 10:01 AM
A.R.T
A.R.T - avatar
8 odpowiedzi
+ 1
One question, does your code only has numbers in lines like 12 98 2662 ?? If yes, then the problem with your code is that file.readlines() method returns a list separated by newlines. But the '\n' characters are not removed. So if the content of your file is 22 44 66 88 The method, file.readlines() will return ['22\n', '44\n', '66\n', '88\n']. So if the input is '44', the in keyword will only check for '44' and not '44\n', and will thus return False. What you can do is add a for loop after the line 'data = myfile.readlines()', which iterates through the list and use .strip() method on each element of the list. string.strip() method removes any whitespace or newline characters before or after the string. So "44\n".strip() will return " 44".
11th May 2020, 12:38 PM
XXX
XXX - avatar
+ 3
A.R.T, did you make a try by yourself? Please link your code here, so that we can give you the required help. Thanks!
11th May 2020, 10:45 AM
Lothar
Lothar - avatar
+ 1
You can read a file as a string and just use the 'in' keyword to test if the string is in the file content.
11th May 2020, 10:03 AM
XXX
XXX - avatar
0
my main code is something like this upper code but it doesn`t work
11th May 2020, 12:16 PM
A.R.T
A.R.T - avatar
0
do we have another way to check existing object in files expect using " in " ?
11th May 2020, 12:18 PM
A.R.T
A.R.T - avatar
0
Thank you so much my problem solved
11th May 2020, 1:20 PM
A.R.T
A.R.T - avatar