ディレクトリもファイル名も全て出力
import glob
import os
path = "./dirname"
list1 = os.listdir(path)
print(list1)
ディレクトリ名だけを出力
import glob
import os
path = "./dirname"
files = os.listdir(path)
files_dir = [f for f in files if os.path.isdir(os.path.join(path, f))]
print(files_dir)
.isdir()
パスが存在しているディレクトリ(フォルダ)であるかどうかを確認する。
ファイル名だけを取得して降順に出力する
import os
path = "./dirname"
folderfile = os.listdir(path)
file = [f for f in folderfile if os.path.isfile(os.path.join(path, f))]
newlist = sorted(file, reverse=True)
print(file)
数字のファイル名を1つずつずらして名前変更
1.txt ⇒ 2.txt
2.txt ⇒ 3.txt
3.txt ⇒ 4.txt
import os
path = "./dirname"
folderfile = os.listdir(path)
file = [f for f in folderfile if os.path.isfile(os.path.join(path, f))]
newlist = sorted(file, reverse=True)
for f in newlist:
basename_without_ext = int(os.path.splitext(os.path.basename(f))[0])
before_name = os.path.join(path,f)
after_name = os.path.join(path, str(basename_without_ext + 1) + os.path.splitext(os.path.basename(f))[1])
os.rename(before_name,after_name)
コメント