Check existence of file

Contents

Output

Found: ./a.txt
Not Found: ./b.txt


Prerequisites

Create a.txt at the same directory of program.


Code examples


JavaScript

const fs = require('fs')
base_dir = __dirname
const exist_file = base_dir + '/a.txt'
const not_exist_file = base_dir + '/b.txt'
if(fs.existsSync(exist_file)) { 
  console.log("Found: " + exist_file)
}
if(!fs.existsSync(not_exist_file)) { 
  console.log("Not Found: " + not_exist_file);
}

Perl

use strict;
use File::Basename;
my $exit_file = dirname(__FILE__).'/a.txt';
my $not_exist_file = dirname(__FILE__).'/b.txt';
if(-f $exit_file) {
  print "Found: ".$exit_file."\n";
}
unless(-f $not_exist_file) {
  print "Not Found: ".$not_exist_file."\n";
}

PHP

<?php
$exist_file = dirname(__FILE__).'/a.txt';
$not_exist_file = dirname(__FILE__).'/b.txt';
if(file_exists($exist_file) ) {
  print "Found: ".$exist_file."\n";
}
if(!file_exists($not_exist_file)) {
  print "Not Found: ".$not_exist_file."\n";
}

Python

import os
base_dir = os.path.dirname(__file__)
if not base_dir:
  base_dir = "."
exit_file = base_dir + '/a.txt'
not_exist_file = base_dir + '/b.txt'
if(os.path.exists(exit_file)):
  print("Found: " + exit_file)
if(not os.path.exists(not_exist_file)):
  print("Not Found: " + not_exist_file)

Ruby

base_dir = File.dirname(__FILE__)
exit_file = base_dir + '/a.txt'
not_exist_file = base_dir + '/b.txt'
if(File.exist?(exit_file)) 
  puts("Found: " + exit_file)
end

if(!File.exist?(not_exist_file)) 
  puts("Not Found: " + not_exist_file);
end

Shell

base_dir=$(cd $(dirname $0); pwd);
exist_file=$base_dir'/a.txt';
not_exist_file=$base_dir'/b.txt';
if [ -f $exist_file ]; then
  echo "Found: "$exist_file;
fi
if [ ! -f $not_exist_file ]; then
  echo "Not Found: "$not_exist_file;
fi