+ 1
Checking file objects
How I can check a specific object(like a number) is existing in my file ???
8 Answers
+ 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".
+ 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!
+ 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.
0
my main code is something like this upper code but it doesn`t work
0
do we have another way to check existing object in files expect using " in " ?
0
Thank you so much
my problem solved