[英]I'm trying to search multiple directories with hundreds of different text files with random text in them, but I'm struggling
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.每个文本文件中都有大量随机字母和符号,我的任务是查找某些信息,例如“HSBC”和“91274163”等。 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.不应该是os.path.join(dirs, filename)
而是os.path.join(root, filename)
。
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编辑:错别字,os.join -> os.path.join
add the changes in your first function在您的第一个 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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.