2017-11-22 6 views
2

私はインタビューに出席し、あるディレクトリから別のディレクトリに移動して.htmlファイルだけを削除するスクリプトを書くように頼んだ。 今私はos.remove()を使ってこれをやろうとしました。あるディレクトリから別のディレクトリに移動して、Pythonで '.html'ファイルのみを削除するにはどうすればいいですか?

def rm_files(): 
    import os 
    from os import path 
    folder='J:\\Test\\' 
    for files in os.listdir(folder): 
     file_path=path.join(folder,files) 
     os.remove(file_path) 

私はここに直面しています問題は、その後、私はグロブを使用してみました、私は私のディレクトリに

のみ.htmlファイルを削除する方法を見つけ出すことができないということである:以下のコードです。コードは次のとおりです。

globを使用して
def rm_files1(): 
    import os 
    import glob 
    files=glob.glob('J:\\Test\\*.html') 
    for f in files: 
     os.remove(f) 

私は.htmlファイルを削除することができますが、それでも私は、あるディレクトリから別のディレクトリに移動するロジックを実装する方法を見つけ出すことはできません。

それに加えて、os.remove()を使用して特定のファイルタイプを削除する方法を教えてください。

ありがとうございます。

+0

Pythonのタグをスパムしないでください。おそらくPython-3.x **と** python2.7は必要ありません。 –

答えて

2

どちらの方法でも動作するはずです。ディレクトリの移動はかなり簡単です

def rm_files(): 
    import os 
    from os import path 
    folder='J:\\Test\\' 
    for files in os.listdir(folder): 
     file_path=path.join(folder,files) 
     if file_path.endswith(".html"): 
      os.remove(file_path) 

それともglobを好む場合、::このようなos.chdir(path)

def rm_files1(): 
    import os 
    os.chdir('J:\\Test') 
    import glob 
    files=glob.glob('J:\\Test\\*.html') 
    for f in files: 
     os.remove(f) 

globを取っているので、それが不要なようだけどそうのような最初の方法については、あなたは可能性だけでstring.endswith(suffix)とにかく絶対パス。あなたの問題は、次の手順で説明することができ

import sys 
import os 
from os import listdir 

directory = "J:\\Test\\" 
test = os.listdir(directory) 

for item in test: 
    if item.endswith(".html"): 
     os.remove(os.path.join(directory, item)) 
1

  • 特定のディレクトリに移動します。これは、すべての* .htmlファイルのグラブリストos.chdir()
  • グラブリストを使用して行うことができます。 glob.glob('*.html')
  • ファイルを削除してください。一緒にすべてを置くos.remove()

使用:

import os 
import glob 
import sys 

def remove_html_files(path_name): 

    # move to desired path, if it exists 
    if os.path.exists(path_name): 
     os.chdir(path_name) 
    else: 
     print('invalid path') 
     sys.exit(1) 

    # grab list of all html files in current directory 
    file_list = glob.glob('*.html') 

    #delete files 
    for f in file_list: 
     os.remove(f) 

    #output messaage 
    print('deleted '+ str(len(file_list))+' files in folder' + path_name) 


# call the function 
remove_html_files(path_name) 
2

この使用endswith()関数のようにあなたが行うことができますos.remove()とディレクトリ内のすべてのhtmlのファイルを削除するには

関連する問題