用Python时报错No such file or directory

程序目的:在一个文件下查找包含特定关键词的文件,如文件名中包含'CAT'的文件,并复制到指定文件夹下

import os
import shutil


src_dir_path = r'F://WTW dataset/train/train\images'  # 源文件夹   修改1

to_dir_path = r'C://Users/PC/Desktop//图像'

key = '1'  # 关键词   修改3

if os.path.exists(src_dir_path):
    for file in os.listdir(src_dir_path):

        logfile = open(file, 'r')
        lines = logfile.readlines()
        for line in lines:
            if line.find(key) != -1:
                shutil.copy(src_dir_path + '/' + file, to_dir_path + '/' + file)

结果报错:
File "F:\learn_pytorch\xml\1.py", line 14, in
logfile = open(file, 'r')
FileNotFoundError: [Errno 2] No such file or directory: '-a6BCtn-SHODim5RQbTWwQAAACMAAQED.jpg'

第14行打开file文件那里,添加要访问的原路径即可,即使用绝对路径的方式访问文件。

修改如下:

参考链接:


python 判断字符串是否包含子字符串_python 字符串包含_mnasd的博客-CSDN博客 第一种方法:instring = 'helloworld'if 'world' in string:  print 'Exist'else:  print 'Not exist'第二种方法:findstring = 'helloworld'if string.find(’world‘) == 5: #5的意思是world字符从那个序开始,因为w位于第六个,及序为5,... https://blog.csdn.net/mnasd/article/details/80398682


import os
import shutil
 
 
src_dir_path = r'D:\testfile'  # 源文件夹   修改1
 
to_dir_path = r'D:\savefile'
 
key = 'cat'  # 关键词   修改3

 # https://blog.csdn.net/Elvirangel/article/details/82467220
if os.path.exists(src_dir_path):
    for file in os.listdir(src_dir_path):

       # print("file=",file)
       # 打开file文件,添加一个路径,使用绝对路径的方式访问
        logfile = open(src_dir_path + '/' +file, 'r')
        lines = logfile.readlines()
        for line in lines:
            if line.find(key) != -1:
                shutil.copy(src_dir_path + '/' + file, to_dir_path + '/' + file)
                break



img

这个错误是因为文件夹中没有找到相应的文件,可能是因为文件名或路径不正确。
检查文件路径和文件名是否正确,并确保文件夹中存在需要的文件。