Handling a .txt text - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Handling a .txt text (/thread-23623.html) |
Handling a .txt text - reinalazaro - Jan-09-2020 Hi, Folks! I'm trying to open a .txt file and find a line with a specific expression but the return isn't what I expected: f = open("file.txt", "r") for line in f: if "Net" in line: print(line) else: print("Didn't find") f.close()So, what i get is a lot of "Didn't find" but I know that there's this expression in the file. And, I noticed that if i ask for just one caracter, like "N" instead the "Net", the code returns lines with it. RE: Handling a .txt text - ichabod801 - Jan-09-2020 What do you get if you take out lines 8 and 9? Are you sure 'Net' is in the line with that capitalization? RE: Handling a .txt text - Clunk_Head - Jan-09-2020 if "Net" in line or 'net' in line:Is it because you need to look for "net" with a lowercase 'n' too? RE: Handling a .txt text - sandeep_ganga - Jan-09-2020 Try this to see if helps, f = open("file.txt", "r") for line in f: #print(line.split(' ')) #splitting the line to list before compare for item in line.split(' '): if "NET" in item.upper(): print(line) else: pass f.close() Best Regards,Sandeep GANGA SANDEEP KUMAR RE: Handling a .txt text - perfringo - Jan-09-2020 I suggest to use different style for opening files (using 'with'). In order to verify processing all rows one can use enumerate and printing out: with open('for_net.txt', 'r') as f: for i, row in enumerate(f, start=1): if 'net' in row.lower(): print(f'Row #{i} contains "net": {row.strip()}') else: print(f'Row #{i} does not contain "net"')if 'for_net.txt' contains following four rows: Quote:This is not Code will output:
RE: Handling a .txt text - reinalazaro - Jan-11-2020 Thank you guys for the help! I'm moving forward with your tips, but it breaks me another issue. f = open("file.txt", "r") for line in f: for item in line.split(' '): if "NET" in item.upper(): print(line) else: pass f.close()When I open a .txt with more data the return of this code is the error below at PyCharm: I'm wondering there is something wrong in the .txt file but there will be a way to treat this "decode" error. Thank you again!! PS.: I liked the way to open the file using 'with'. RE: Handling a .txt text - Clunk_Head - Jan-11-2020 Try: f = open("file.txt", encoding='utf-8', errors='ignore') RE: Handling a .txt text - reinalazaro - Jan-11-2020 It works!! |