![](/img/trans.png)
[英]Python: How do I output all the text contents of a directory containing .txt files as a list?
[英]How do I search all text files in directory for a string and place the found result in a text file in Python
我正在嘗試編寫一些 Python 代碼來查看目錄中的 all.txt 文件以及包含特定字符串的任何文件,將 append 文件名轉換為 a.txt 文件。
我目前有以下代碼在我 select 單個文件時有效:
with open('FW_ (Big) Data Engineer.msg datatext.txt') as f:
if "Data Engineer" in f.read():
f = open("Data Engineer.txt","a+")
f.write("Found it, but I would rather have the file name here")
f.close()
假設目錄路徑是“C:\Users\me\textfiles”,我似乎找不到循環遍歷該目錄中所有文件的方法,查找字符串並將文件名寫入例如“ Data Engineer.txt”如果它應該屬於那里。
我已經嘗試將我的路徑定義為變量,但我還沒有找到一個可行的解決方案(嘗試過 os.scandir 和 Path),我還沒有找到一個可行的解決方案來遍歷該目錄中的所有文件。 我知道 f.write 需要一個字符串,但我認為將變量放在 str() 之間可以解決這個問題。
嘗試這個:
import os
# Remember to change these
directory = "test";
text = "Test";
def search(dirname):
array = [];
for i in os.listdir(dirname):
i = os.path.join(dirname, i);
if(os.path.isdir(i)):
x = search(i);
if(not x):
continue;
array = array + x;
else:
if(text in open(i, "r").read()):
do_something();
search(directory);
這也將在子目錄中搜索。
您可以使用以下代碼遍歷文件夾:
import os
for filename in os.listdir(directory):
with open (directory+'/'+filename) as f:
#your code here
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.