1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonでOSの操作をする

Posted at

OS操作

OS操作とは、ファイルの複製やパス管理、ディレクトリ操作などのこと

import os
import glob

ファイルの一覧の取得

フォルダ内のファイル一覧を取得するには、glob.glob関数を使用する。
引数には、検索する条件を指定する。
検索時、ワイルドカード*を使用してファイルの種類などを絞り込むことも可能。
戻り値はファイルの一覧がリストで返される。

import glob
  
#フォルダの中のファイルをすべて取得
file_list = glob.glob("ファイルパス")
print(file_list)
  
#フォルダの中の.csvファイルをすべて取得
excel_list = glob.glob("ファイルパス")
print(excel_list)

ファイルパスの制御

```os.path``モジュールはファイルのパスに関する関数を集めたモジュール、ファイルの絶対パスの取得や、ファイル名の取得、拡張子なしのファイル名の取得などができる。

import os
import glob
  
file_list = glob.glob("ファイルパス")
  
# パスからファイル名だけを抽出して表示
for f in file_list:
    basename = os.path.basename(f)
    print(basename)
  
print("*"*10)
  
# パスからファイル名だけを抽出して拡張子なしで表示
for f in file_list:
    basename_without_ext = os.path.splitext(os.path.basename(f))[0]

ファイル名の変更

os.rename関数

import os
  
os.rename("ファイルパス", "ファイルパス")
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?