【问题标题】:Unable to rename all the files in a folder无法重命名文件夹中的所有文件
【发布时间】:2013-06-20 02:12:10
【问题描述】:

我一直在尝试使用以下 sn-p 更改文件夹中所有图片文件的文件扩展名:

$dh = opendir('JS2C'); 
$files = array(); 
while (($file = readdir($dh)) !== false) { 
    if($file !== '.' && $file !== '..') {
        $file = pathinfo($file);
        rename($file, $new . '.jpg');
    }
}

我收到以下警告消息:

SCREAM: Error suppression ignored for
Warning: rename(ANAZODO.gif,ANAZODO.jpg): 
The system cannot find the file specified. (code: 2) in C:\wamp2\www\ckcportal\batch2.php on ...

包含文件的文件夹与PHP 脚本位于同一文件夹中。

【问题讨论】:

    标签: php rename file-rename


    【解决方案1】:

    您缺少要重命名的目录

    $d = 'JS2C/'
    $dh = opendir($d); 
    while (($file = readdir($dh)) !== false) { 
        if($file !== '.' && $file !== '..') {
            //$file_no_ext = substr($file, 0,strrpos($file,'.'));// before php 5.2 
    
            $path_parts = pathinfo($file); // php 5.2
            $file_no_ext =  $path_parts['filename'];  // php 5.2
    
           rename($d.$file, $d.$file_no_ext . '.jpg');
        }
    }
    

    【讨论】:

      【解决方案2】:

      您必须提供完整路径,从您收到的错误来看,您似乎只是在提供文件名。

      rename('/path/to/old/file', '/path/to/new/file');
      

      你为什么使用$file = pathinfo($file);pathinfo 创建一个关联。来自$file 信息的数组,它应该为您提供完整路径。如果你把它拿出来,它应该可以工作。

      除非你需要遵循:

      $info = pathinfo($file);
      $path = $info['dirname']
      
      $new_file = $path . '/' . 'newfile.ext';
      
      rename($file, $new_file);
      

      【讨论】:

        猜你喜欢
        • 2013-04-24
        • 2016-07-15
        • 1970-01-01
        • 1970-01-01
        • 2016-07-04
        • 2015-10-20
        • 1970-01-01
        相关资源
        最近更新 更多