簡體   English   中英

如何從一個目錄移動到另一個目錄並僅刪除python中的'.html'文件?

[英]How to move from one directory to another and delete only '.html' files in python?

我參加了一次采訪,他們要求我編寫一個腳本,從一個目錄移動到另一個目錄,並僅刪除.html文件。 現在,我首先嘗試使用os.remove() 以下是代碼:

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)

使用glob我可以刪除.html文件,但仍然無法弄清楚如何實現從一個目錄移動到另一個目錄的邏輯。

有人可以幫我找出如何使用os.remove()刪除特定文件類型的方法嗎?

謝謝。

這些方法均應起作用。 對於第一種方法,您可以像這樣使用string.endswith(suffix)

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無論如何都走絕對路徑。

您的問題可以在以下步驟中進行描述。

  • 移到特定目錄 這可以使用os.chdir()
  • 抓取所有* .html文件的列表 使用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)

要使用os.remove()刪除目錄中的所有html文件,您可以使用endswith()函數執行以下操作

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 ) )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM