社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在python中查找包含特定字符串的循环文件?[关闭]

cobra1994 • 5 年前 • 1440 次点击  

我有上百个包含字符串的文件 "_done" ,就像 "file1_done.dat","file2_done.dat",...,"file800_done.dat" . 我想阅读这些文件并做一些修改。如何循环浏览这些文件?我更喜欢for循环,我希望python脚本尽可能简单!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51619
 
1440 次点击  
文章 [ 3 ]  |  最新文章 5 年前
chmod777
Reply   •   1 楼
chmod777    5 年前

循环浏览以“完成”结尾的文件:

 for name in files:
        if name.endswith('_done'):
            # do what you want

编辑: 要获取当前目录中的文件列表,请执行以下操作:

import os

dir = '/dir' # paste your current directory here

# the required list is 'files' below:
files = [ f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir,f)) ]
Zebra8844
Reply   •   2 楼
Zebra8844    5 年前

如果模式(“完成”)可以位于文件名中的其他位置,则可以执行以下操作:

    import os

    directory = '.' # change to your own directory
    for filename in os.listdir(directory):
        if filename.__contains__("__done"): 
             print(os.path.join(directory, filename))
             # continue with your process
azro
Reply   •   3 楼
azro    5 年前

您可以遍历文件夹的文件,并检查 _done 是以这个名字直接操作的

from os import listdir
from os.path import join

for file in listdir("mydirectory"):
    if "_done" in file:
        full_path = join("mydirectory", file)

或者准备文件列表,然后遍历它们:

files_done = [join("mydirectory", file) for file in listdir("mydirectory") 
                                        if "_done" in file]
for full_path in files_done:
    pass