Skip to content

File and folder related operations

Different programming languages have different APIs for file and directory operations. It’s easier to forget when you don’t use them often, then it takes a lot of time to search for information. This article records the APIs of file-related operations in Shell/C++/Python languages for future reference.

Get current directory

Shell

current_dir=$(pwd)

C++

std::string current_dir = std::filesystem::current_path().string();

Python

current_dir = os.path.abspath(os.getcwd())

Change current directory

Shell

cd dir_path

C++

std::filesystem::current_path(dir_path);

Python

os.chdir(dir_path)

Get current source file’s directory

Shell

src_dir=$(cd "$(dirname "$0")";pwd)

C++

std::string src_dir = __FILE__;

Python

src_dir = os.path.abspath(__file__)

If file exists

Shell

if [ ! -f "file_path" ]; then
echo file exists.
fi

C++

std::filesystem::exists(file_path);

Python

os.path.exists("file_path")

If directory exists

Shell

if [ ! -d "dir_path" ]; then
echo file exists.
fi

C++

std::filesystem::exists(dir_path);

Python

os.path.exists("dir_path")

Delete file

Shell

rm file_path

C++

std::filesystem::remove(file_path);

Python

os.remove(file_path)

Create directory

Shell

mkdir dir_path

C++

std::filesystem::create_directories(dir_path);

Python

os.makedirs(dir_path)

Delete directory

Shell

rm -r dir_path

C++

std::filesystem::remove_all(dir_path);

Python

shutil.rmtree(dir_path)

Move directory

Shell

mv old_path new_path

C++

std::filesystem::rename("old_path", "new_path");

Python

shutil.move("old_path", "new_path")

Get file’s directory

Shell

dirname file_path

C++

std::filesystem::path(file_path);

Python

dir_path = os.path.dirname(file_path)

Get file basename

Shell

basename file_path

C++

std::filesystem::filename(file_path);

Python

os.path.basename(file_path)

Get file extension

Shell

echo "file_path" | cut -d'.' -f2

C++

std::filesystem::extension(file_path);

Python

os.path.splittext(path)[-1]
Leave a Reply