ディレクトリの存在有無を確認

Contents [hide]

出力結果

1
2
Found: ./a_dir
Not Found: ./b_dir

前準備

プログラムと同じディレクトリにa_dirというディレクトリを作っておく

プログラム例

JavaScript

1
2
3
4
5
6
7
8
9
10
const fs = require('fs')
base_dir = __dirname
const exist_dir = base_dir + '/a_dir'
const not_exist_dir = base_dir + '/b_dir'
if(fs.existsSync(exist_dir)) {
  console.log("Found: " + exist_dir)
}
if(!fs.existsSync(not_exist_dir)) {
  console.log("Not Found: " + not_exist_dir)
}

Perl

1
2
3
4
5
6
7
8
9
10
use strict;
use File::Basename;
my $exit_dir = dirname(__FILE__).'/a_dir';
my $not_exist_dir = dirname(__FILE__).'/b_dir';
if(-d $exit_dir) {
  print "Found: ".$exit_dir."\n";
}
unless(-d $not_exist_dir) {
  print "Not Found: ".$not_exist_dir."\n";
}

PHP

1
2
3
4
5
6
7
8
9
<?php
$exist_dir = dirname(__FILE__).'/a_dir';
$not_exist_dir = dirname(__FILE__).'/b_dir';
if(file_exists($exist_dir) ) {
  print "Found: ".$exist_dir."\n";
}
if(!file_exists($not_exist_dir)) {
  print "Not Found: ".$not_exist_dir."\n";
}

Python

1
2
3
4
5
6
7
8
9
10
import os
base_dir = os.path.dirname(__file__)
if not base_dir:
  base_dir = "."
exit_dir = base_dir + '/a_dir'
not_exist_dir = base_dir + '/b_dir'
if(os.path.exists(exit_dir)):
  print("Found: " + exit_dir)
if(not os.path.exists(not_exist_dir)):
  print("Not Found: " + not_exist_dir)

Ruby

1
2
3
4
5
6
7
8
9
10
base_dir = File.dirname(__FILE__)
exit_dir = base_dir + '/a_dir'
not_exist_dir = base_dir + '/b_dir'
if(File.exist?(exit_dir))
  puts("Found: " + exit_dir)
end
 
if(!File.exist?(not_exist_dir))
  puts("Not Found: " + not_exist_dir);
end

Shell

1
2
3
4
5
6
7
8
9
base_dir=$(cd $(dirname $0); pwd);
exist_dir=$base_dir'/a_dir';
not_exist_dir=$base_dir'/b_dir';
if [ -d $exist_dir ]; then
  echo "Found: "$exist_dir;
fi
if [ ! -d $not_exist_dir ]; then
  echo "Not Found: "$not_exist_dir;
fi

プログラミング言語比較サイトProgrammingLang.comでは、同じ問題を複数のプログラミング言語がそれぞれどのような記述で解決できるのかの例を提供。
複数の言語を比較し、貴方の問題を解決するのに最適な言語の選択と、その言語での解法を得る事を手助けします。
全問題カバー: JavaScript Perl PHP Python Ruby | 一部: C C# C++ Go Java Rust Shell
 
問題解法大分類(50音順)
Class | 時間 | 数値 | System | Database | Test | Network | 配列 | ファイルシステム | 変数 | 文字列
その他役立ちコンテンツ

※当サイトではアフィリエイトプログラムを利用して商品を紹介しています。