ファイルを削除するには
ファイルを削除する基本形を各言語で示す。
既に無いファイルを消したときの扱い、空でないディレクトリを中身ごと消す方法までを扱う。
公開:
選んだ言語は、ほかのサンプルコードを開いたときも最初に表示する。
Python
import os
from pathlib import Path
Path("a.txt").write_text("x", encoding="utf-8")
os.remove("a.txt") # ファイルを削除する
print(Path("a.txt").exists()) # False
try:
os.remove("a.txt") # 既に無いと失敗する
except FileNotFoundError as e:
print(type(e).__name__) # FileNotFoundError
Path("a.txt").unlink(missing_ok=True) # 無くてもエラーにしない(3.8 以降)
Path("d/sub").mkdir(parents=True, exist_ok=True)
Path("d/sub/b.txt").write_text("x", encoding="utf-8")
try:
os.rmdir("d/sub") # 空でないディレクトリは os.rmdir では消せない
except OSError as e:
print(type(e).__name__) # OSError
import shutil
shutil.rmtree("d") # 中身ごと削除する
print(Path("d").exists()) # Falseファイルの削除は os.remove で行い、pathlib の Path.unlink でも同じことができる。
既に無いファイルは FileNotFoundError になるので、無くてもよい場面では unlink に missing_ok=True を渡す。
ディレクトリは中身が空でないと os.rmdir で消せず、shutil.rmtree なら中身ごと消せる。
JavaScript
import { writeFile, unlink, rm, mkdir, access } from "node:fs/promises";
await writeFile("a.txt", "x");
await unlink("a.txt"); // ファイルを削除する
try {
await unlink("a.txt"); // 既に無いと失敗する
} catch (err) {
console.log(err.code); // ENOENT
}
await rm("a.txt", { force: true }); // 無くてもエラーにしない
await mkdir("d/sub", { recursive: true });
await writeFile("d/sub/b.txt", "x");
try {
await rm("d"); // recursive なしでディレクトリを消そうとすると失敗する
} catch (err) {
console.log(err.code); // ERR_FS_EISDIR
}
await rm("d", { recursive: true, force: true }); // 中身ごと削除する
console.log(await access("d").then(() => true, () => false)); // falsefs/promises の unlink は 1 つのファイルを消し、既に無いと code が ENOENT のエラーになる。
rm に force: true を渡すと、無くてもエラーにならない。
ディレクトリは recursive: true を付けないと消せないので、中身ごと消すときだけ付ける。
TypeScript
import { writeFile, unlink, rm, mkdir, access } from "node:fs/promises";
// 無くてもエラーにしない削除。ENOENT 以外のエラーは握りつぶさず投げ直す
async function removeIfExists(path: string): Promise<boolean> {
try {
await unlink(path);
return true;
} catch (err) {
if ((err as NodeJS.ErrnoException).code === "ENOENT") return false;
throw err;
}
}
await writeFile("a.txt", "x");
console.log(await removeIfExists("a.txt")); // true(消した)
console.log(await removeIfExists("a.txt")); // false(既に無かった)
await mkdir("d/sub", { recursive: true });
await writeFile("d/sub/b.txt", "x");
await rm("d", { recursive: true, force: true }); // 中身ごと削除する
console.log(await access("d").then(() => true, () => false)); // false無くてもよい削除は、unlink の ENOENT だけを握りつぶし、権限不足などの別のエラーは投げ直す形にすると、本当の失敗を見逃さない。
catch の err は unknown 型なので、NodeJS.ErrnoException に絞り込んでから code を読む。
Go
package main
import (
"errors"
"fmt"
"io/fs"
"os"
)
func main() {
os.WriteFile("a.txt", []byte("x"), 0o644)
fmt.Println(os.Remove("a.txt")) // <nil>
// 既に無いと失敗する
err := os.Remove("a.txt")
fmt.Println(errors.Is(err, fs.ErrNotExist)) // true
os.MkdirAll("d/sub", 0o755)
os.WriteFile("d/sub/b.txt", []byte("x"), 0o644)
// os.Remove は空でないディレクトリを消せない
fmt.Println(os.Remove("d") != nil) // true
// os.RemoveAll は中身ごと消し、対象が無くても nil を返す
fmt.Println(os.RemoveAll("d")) // <nil>
fmt.Println(os.RemoveAll("d")) // <nil>
_, err = os.Stat("d")
fmt.Println(errors.Is(err, fs.ErrNotExist)) // true
}os.Remove はファイルと空のディレクトリを消し、対象が無いと errors.Is と fs.ErrNotExist で見分けられるエラーを返す。
空でないディレクトリは os.Remove では消せないため、中身ごと消すときは os.RemoveAll を使う。os.RemoveAll は対象が無くても nil を返すので、何度呼んでも安全である。
Rust
use std::fs;
use std::io::ErrorKind;
use std::path::Path;
fn main() -> std::io::Result<()> {
fs::write("a.txt", "x")?;
fs::remove_file("a.txt")?; // ファイルを削除する
// 既に無いと NotFound になる
let err = fs::remove_file("a.txt").unwrap_err();
println!("{:?}", err.kind()); // NotFound
// 無くてもエラーにしない
match fs::remove_file("a.txt") {
Err(e) if e.kind() == ErrorKind::NotFound => {}
other => other?,
}
fs::create_dir_all("d/sub")?;
fs::write("d/sub/b.txt", "x")?;
// remove_dir は空でないディレクトリを消せない
println!("{}", fs::remove_dir("d").is_err()); // true
fs::remove_dir_all("d")?; // 中身ごと削除する
println!("{}", Path::new("d").exists()); // false
Ok(())
}fs::remove_file は 1 つのファイルを消し、無いと ErrorKind::NotFound のエラーを返す。
無くてもよい場面では、match のガードで NotFound だけを読み飛ばし、それ以外のエラーは ? で伝播させる。
空でないディレクトリは fs::remove_dir では消せないので、中身ごと消すときは fs::remove_dir_all を使う。
Java
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws Exception {
Path file = Path.of("a.txt");
Files.writeString(file, "x");
Files.delete(file); // ファイルを削除する
try {
Files.delete(file); // 既に無いと例外になる
} catch (NoSuchFileException e) {
System.out.println("NoSuchFileException");
}
System.out.println(Files.deleteIfExists(file)); // false(無くても例外にしない)
Path dir = Path.of("d/sub");
Files.createDirectories(dir);
Files.writeString(dir.resolve("b.txt"), "x");
try {
Files.delete(Path.of("d")); // 空でないディレクトリは消せない
} catch (DirectoryNotEmptyException e) {
System.out.println("DirectoryNotEmptyException");
}
// 中身ごと消すには、深いものから順に 1 つずつ消す
try (Stream<Path> walk = Files.walk(Path.of("d"))) {
for (Path p : (Iterable<Path>) walk.sorted(Comparator.reverseOrder())::iterator) {
Files.delete(p);
}
}
System.out.println(Files.exists(Path.of("d"))); // false
}
}Files.delete は対象が無いと NoSuchFileException を投げ、空でないディレクトリには DirectoryNotEmptyException を投げる。
無くてもよい場面では、例外の代わりに true か false を返す Files.deleteIfExists を使う。
標準ライブラリには中身ごと消すメソッドが無いため、Files.walk で集めたパスを深いものから順に 1 つずつ消す。
C#
using System;
using System.IO;
File.WriteAllText("a.txt", "x");
File.Delete("a.txt"); // ファイルを削除する
File.Delete("a.txt"); // 既に無くても例外にならない
Console.WriteLine(File.Exists("a.txt")); // False
Directory.CreateDirectory("d/sub");
File.WriteAllText("d/sub/b.txt", "x");
try
{
Directory.Delete("d"); // 空でないディレクトリは消せない
}
catch (IOException e)
{
Console.WriteLine(e.GetType().Name); // IOException
}
Directory.Delete("d", true); // 中身ごと削除する
Console.WriteLine(Directory.Exists("d")); // False
try
{
Directory.Delete("d", true); // ディレクトリが無いと例外になる
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine(e.GetType().Name); // DirectoryNotFoundException
}File.Delete は対象のファイルが無くても例外を投げないので、存在確認は要らない。Directory.Delete は空でないディレクトリだと IOException になり、第 2 引数に true を渡すと中身ごと消せる。
ディレクトリ自体が無いときは、true を渡しても DirectoryNotFoundException になる。
つまずき
消そうとしたファイルが無いときの挙動は言語で違う。
Python の os.remove、Node.js の unlink、Go の os.Remove、Rust の fs::remove_file、Java の Files.delete はエラーや例外になる。
C# の File.Delete は何も起きない。
無くてもよい場面では、Python の missing_ok=True、Node.js の rm の force: true、Java の Files.deleteIfExists のように、専用の書き方を使う。
ディレクトリは中身ごと消すかどうかで書き方が変わる
空のディレクトリを消す関数は、中身があると失敗する。
中身ごと消すには、次のように専用の書き方を選ぶ。
- Python は
shutil.rmtree - Node.js は rm に
recursive: true - Go は
os.RemoveAll - Rust は
fs::remove_dir_all - C# は
Directory.Deleteの第 2 引数に true - Java は標準ライブラリに無いので、
Files.walkで深いものから順に消す
再帰的な削除は元に戻せないため、渡すパスを変数から作るときは、空文字や意図しない親ディレクトリになっていないかを先に確かめる。