14
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonでlinuxコマンドlsの実行結果をlistに保存

Last updated at Posted at 2017-09-07

listdir

import os
ls_file_name = os.listdir()

scandir

import os

filenames = [f.name for f in os.scandir()]


# .から始まる特殊ファイルを除く
filenames = [f.name for f in os.scandir() if not f.name.startswith('.')]

# ディレクトリのみ 
filenames = [f.name for f in os.scandir() if f.is_dir()]

# ファイル のみ
filenames = [f.name for f in os.scandir() if f.is_file()]
  • python公式でlistdirよりscandirが推奨されている。
  • 以下のgrep使うより、listdir,scandirを使ってreで絞ったほうがいいかも。

subprocess

import subprocess as sp
cmd = "ls" 
proc= sp.Popen(cmd, shell=True, stdout=sp.PIPE, stderr=sp.PIPE)
std_out, std_err = proc.communicate()
# byte文字列で返るのでstrに
ls_file_name = std_out.decode('utf-8').rstrip().split('\n')

また、以下のように、簡単に書ける。

ls_file_name = sp.check_output("ls | grep foo", shell=True).decode('utf-8').strip().split('\n')

ただし、今回のように実行したいコマンドを1つの文字列で渡す場合は、shell=Trueにしなければいけない。

14
13
4

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
14
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?