I have hundreds of little text files in multiple folders. In each text file is loads of random letters and symbols and I have been tasked with finding certain information like "HSBC" and "91274163" and others. I am very new to coding and I am struggling quite a lot, I do not have long left to complete this so if anyone can help I'd appreciated
import os
FILENAMES=[]
for root, dirs, files in os.walk(r"****MY PATH****"):
for filename in files:
if filename.endswith(".txt"):
FILENAMES.append(filename)
print(filename)
print('\n')
This is the first part of my code, Which displays all the text files and then exits.
for FILENAME in FILENAMES:
print(FILENAME," contains the following function:\n")
f1=open(FILENAME,'r')
for line in f1:
if ("HSBC") in line:
print(line)
else:
pass
print('\n')
f1.close()
As soon as I add this part of the code I get "
f1=open(FILENAME,'r')
^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'File-06Ijg.txt'
I have tried many other scripts, I encounter various different encoding errors etc. At least with this script I can display all the text files so im trying to figure this one out
I'm really sorry, should've tested before answering. Shouldn't be os.path.join(dirs, filename)
but os.path.join(root, filename)
instead.
Try this:
import os
FILENAMES=[]
for root, dirs, files in os.walk(r"****MY PATH****"):
for filename in files:
if filename.endswith(".txt"):
FILENAMES.append(os.path.join(root, filename))
print(filename)
print('\n')
for FILENAME in FILENAMES:
print(FILENAME," contains the following function:\n")
with open(FILENAME,'r', encoding="utf-8") as f1:
for line in f1:
if "HSBC" in line:
print(line)
print('\n')
Edit: Typo, os.join -> os.path.join
add the changes in your first function
import os
FILENAMES=[]
for root, dirs, files in os.walk(r"****MY PATH****"):
for filename in files:
if filename.endswith(".txt"):
# this line with get complete path
file_path = os.path.join(root,filename)
FILENAMES.append(file_path)
print(file_path)
print('\n')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.