sim*_*sim 5 python operating-system
.txt20210624存在于文件中,哪些字符串20210625不在文件中import os
match_str = ['20210624']
not_match_str = ['20210625']
for root, dirs, files in os.walk(path):
for name in files:
if name.endswith((".txt")):
## search files with match_str `20210624` and not_match_str `20210625`
Run Code Online (Sandbox Code Playgroud)
我可以使用 import walk
您可以recursive在glob.glob()方法中设置关键字参数,True以便程序递归搜索文件夹、子文件夹等文件。
from glob import glob
path = 'C:\\Users\\User\\Desktop'
for file in glob(path + '\\**\\*.txt', recursive=True):
with open(file) as f:
text = f.read()
if '20210624' in text and '20210625' not in text:
print(file)
Run Code Online (Sandbox Code Playgroud)
如果您不想打印文件的整个路径;只有文件名,然后:
from glob import glob
path = 'C:\\Users\\User\\Desktop'
for file in glob(path + '\\**\\*.txt', recursive=True):
with open(file) as f:
text = f.read()
if '20210624' in text and '20210625' not in text:
print(file.split('\\')[-1])
Run Code Online (Sandbox Code Playgroud)
为了使用该os.walk()方法,您可以像这样使用该str.endswith()方法(就像您在帖子中所做的那样):
import os
for path, _, files in os.walk('C:\\Users\\User\\Desktop'):
for file in files:
if file.endswith('.txt'):
with open(os.path.join(path, file)) as f:
text = f.read()
if '20210624' in text and '20210625' not in text:
print(file)
Run Code Online (Sandbox Code Playgroud)
并在最大级别的子目录中搜索:
import os
levels = 2
root = 'C:\\Users\\User\\Desktop'
total = root.count('\\') + levels
for path, _, files in os.walk(root):
if path.count('\\') > total:
break
for file in files:
if file.endswith('.txt'):
print(os.path.join(path, file))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
203 次 |
| 最近记录: |