ගොනුවක් හෝ ෆෝල්ඩරයක් මකා දැමිය හැක්කේ කෙසේද?


Answers:


3376
  • os.remove() ගොනුවක් ඉවත් කරයි.

  • os.rmdir() හිස් නාමාවලියක් ඉවත් කරයි.

  • shutil.rmtree() ඩිරෙක්ටරියක් සහ එහි සියලුම අන්තර්ගතයන් මකා දමයි.


Pathපයිතන් 3.4+ pathlibමොඩියුලයේ වස්තූන් ද මෙම උදාහරණ ක්‍රම හෙළි කරයි:

  • pathlib.Path.unlink() ගොනුවක් හෝ සංකේතාත්මක සබැඳියක් ඉවත් කරයි.

  • pathlib.Path.rmdir() හිස් නාමාවලියක් ඉවත් කරයි.


5
වින්ඩෝස් හි os.rmdir () ඉලක්කගත ඩිර් හිස්
නොවූවත්

9
ගොනුව නොපවතී නම්, os.remove()ව්‍යතිරේකයක් විසි කරයි, එබැවින් os.path.isfile()පළමුව පරීක්ෂා කිරීම හෝ a හි එතීම අවශ්‍ය විය හැකිය try.
බෙන් ක්‍රොවෙල්

2
Path.unlink 1 / පුනරාවර්තන 2 / FileNotfoundError නොසලකා හැරීමට විකල්පයක් එක් කිරීමට මම ප්‍රාර්ථනා කරමි.
ජෙරොම්

7
සම්පුර්ණ කිරීම සඳහා ... os.remove()ගොනුවක් නොපවතී නම් විසි කිරීම ව්‍යතිරේකය වේ FileNotFoundError.
PedroA

වන්නේද, os.remove() බහු ගොනු මැකීමට බහු තර්ක මත, හෝ ඔබ එක් එක් ගොනුව සඳහා එක් එක් කාල එය අමතන්න ඇයි?
user742864

296

ගොනුවක් මකා දැමීමට පයිතන් සින්ටැක්ස්

import os
os.remove("/tmp/<file_name>.txt")

හෝ

import os
os.unlink("/tmp/<file_name>.txt")

හෝ

පයිතන් අනුවාදය සඳහා පාත්ලිබ් පුස්තකාලය> 3.5

file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()

Path.unlink (missing_ok = අසත්‍යය)

ගොනුව හෝ සංකේතාත්මක සබැඳිය ඉවත් කිරීමට භාවිතා කරන අන්ලින්ක් ක්‍රමය.

Missing_ok අසත්‍ය නම් (පෙරනිමිය), මාර්ගය නොපවතී නම් FileNotFoundError මතු වේ.
Missing_ok සත්‍ය නම්, FileNotFoundError ව්‍යතිරේකයන් නොසලකා හරිනු ඇත (POSIX rm -f විධානයට සමාන හැසිරීම).
3.8 අනුවාදයේ වෙනස් කරන ලදි: missing_ok පරාමිතිය එකතු කරන ලදි.

හොඳම පුහුණුව

  1. පළමුව, ගොනුව හෝ ෆෝල්ඩරය තිබේදැයි පරීක්ෂා කර බලා එම ගොනුව මකා දමන්න. මෙය ක්‍රම දෙකකින් සාක්ෂාත් කරගත හැකිය:
    a. os.path.isfile("/path/to/file")
    බී. භාවිතexception handling.

සඳහා උදාහරණයos.path.isfile

#!/usr/bin/python
import os
myfile="/tmp/foo.txt"

## If file exists, delete it ##
if os.path.isfile(myfile):
    os.remove(myfile)
else:    ## Show an error ##
    print("Error: %s file not found" % myfile)

ව්‍යතිරේක හැසිරවීම

#!/usr/bin/python
import os

## Get input ##
myfile= raw_input("Enter file name to delete: ")

## Try to delete the file ##
try:
    os.remove(myfile)
except OSError as e:  ## if failed, report it back to the user ##
    print ("Error: %s - %s." % (e.filename, e.strerror))

ගෞරවනීය නිමැවුම

මකා දැමීමට ගොනුවේ නම ඇතුළත් කරන්න: demo.txt
දෝෂය: demo.txt - එවැනි ගොනුවක් හෝ නාමාවලියක් නොමැත.

මකා දැමීමට ගොනුවේ නම ඇතුළත් කරන්න: rrr.txt
දෝෂය: rrr.txt - මෙහෙයුමට අවසර නැත.

මකා දැමීමට ගොනු නාමය ඇතුළත් කරන්න: foo.txt

ෆෝල්ඩරයක් මකා දැමීමට පයිතන් සින්ටැක්ස්

shutil.rmtree()

නිදසුනක් shutil.rmtree()

#!/usr/bin/python
import os
import sys
import shutil

# Get directory name
mydir= raw_input("Enter directory name: ")

## Try to remove tree; if failed show an error using try...except on screen
try:
    shutil.rmtree(mydir)
except OSError as e:
    print ("Error: %s - %s." % (e.filename, e.strerror))

15
ගොනුව පේළි දෙක අතර ඉවත් කිරීමට හෝ වෙනස් කිරීමට හැකි නිසා (TOCTOU: en.wikipedia.org/wiki/Time_of_check_to_time_of_use ) පයිතන් නිතර අසන පැන බලන්න docs.python.org/3/glossary.html#term-eafp
ඇරික් අරුජෝ

85

භාවිත

shutil.rmtree(path[, ignore_errors[, onerror]])

( ෂටිල් පිළිබඳ සම්පූර්ණ ලියකියවිලි බලන්න ) සහ / හෝ

os.remove

සහ

os.rmdir

(මත සම්පූර්ණ ප්රලේඛනය os .)


6
කරුණාකර ඔබගේ ලැයිස්තුවට පාත්ලිබ් අතුරුමුහුණත (පයිතන් 3.4 සිට අලුත්) එක් කරන්න.
පැබෙල්ස්

41

මෙන්න දෙකම භාවිතා කරන ශක්තිමත් ශ්රිතයක් වේ os.removeහා shutil.rmtree:

def remove(path):
    """ param <path> could either be relative or absolute. """
    if os.path.isfile(path) or os.path.islink(path):
        os.remove(path)  # remove the file
    elif os.path.isdir(path):
        shutil.rmtree(path)  # remove dir and all contains
    else:
        raise ValueError("file {} is not a file or dir.".format(path))

8
ISO C remove(path);ඇමතුම අනුකරණය කිරීම සඳහා කේත පේළි 8 ක් .
Kaz

2
Az කාස් කරදරකාරී ලෙස එකඟ වූ නමුත් ගස් සමඟ ගනුදෙනු ඉවත් කරයිද? :-)
සිරෝ සැන්ටිලි ill 冠状 病 六四 事件 法轮功

6
os.path.islink(file_path): දෝෂයක් විය යුතුයos.path.islink(path):
Neo li

33

ඔබ බිල්ට් භාවිතා කළ හැකිය pathlibමොඩියුලය (Python 3.4+ අවශ්යයි, නමුත් PyPI මත පැරණි අනුවාද සඳහා බැක්පෝර්ට්ස් තිබේ: pathlib, pathlib2).

ගොනුවක් ඉවත් කිරීම සඳහා unlinkක්රමයක් තිබේ:

import pathlib
path = pathlib.Path(name_of_file)
path.unlink()

හෝ හිස් ෆෝල්ඩරයක් rmdirඉවත් කිරීමේ ක්‍රමය :

import pathlib
path = pathlib.Path(name_of_folder)
path.rmdir()

3
හිස් නොවන නාමාවලියක් ගැන කුමක් කිව හැකිද?
ප්‍රණස

Ran ප්‍රණසස් අවාසනාවකට pathlibහිස් නොවන නාමාවලි මකා දැමිය හැකි කිසිවක් (දේශීයව) නොමැති බව පෙනේ . කෙසේ වෙතත් ඔබට භාවිතා කළ හැකිය shutil.rmtree. එය වෙනත් පිළිතුරු කිහිපයකම සඳහන් කර ඇති බැවින් මම එය ඇතුළත් කර නැත.
MSeifert

30

පයිතන් හි ගොනුවක් හෝ ෆෝල්ඩරයක් මකා දැමිය හැක්කේ කෙසේද?

පයිතන් 3 සඳහා, ගොනුව සහ නාමාවලිය තනි තනිව ඉවත් කිරීමට, පිළිවෙලින් unlinkසහ වස්තු ක්‍රම භාවිතා කරන්න:rmdir Path

from pathlib import Path
dir_path = Path.home() / 'directory' 
file_path = dir_path / 'file'

file_path.unlink() # remove file

dir_path.rmdir()   # remove directory

ඔබට Pathවස්තූන් සමඟ සාපේක්ෂ මාර්ග භාවිතා කළ හැකි බව සලකන්න , එවිට ඔබට ඔබගේ වර්තමාන වැඩ කරන නාමාවලිය පරීක්ෂා කළ හැකිය Path.cwd.

පයිතන් 2 හි තනි ගොනු සහ නාමාවලි ඉවත් කිරීම සඳහා, පහත ලේබල් කර ඇති කොටස බලන්න.

අන්තර්ගතයන් සහිත නාමාවලියක් ඉවත් කිරීමට, භාවිතා කරන්න shutil.rmtree, සහ මෙය පයිතන් 2 සහ 3 හි ඇති බව සලකන්න:

from shutil import rmtree

rmtree(dir_path)

නිරූපණය

පයිතන් 3.4 හි නව Pathවස්තුව වන්නේ වස්තුවයි.

ඩිරෙක්ටරියක් සහ ගොනුවක් නිර්මාණය කිරීම සඳහා එකක් භාවිතා කරමු. අපි /මාර්ගයේ කොටස් වලට සම්බන්ධ වීමට භාවිතා කරන බව සලකන්න , මෙය මෙහෙයුම් පද්ධති අතර ඇති ගැටළු සහ වින්ඩෝස් හි බැක්ස්ලෑෂ් භාවිතා කිරීමෙන් ඇති වන ගැටලු වටා ක්‍රියා කරයි (එහිදී ඔබට ඔබේ බැක්ස්ලෑෂ් දෙගුණ කිරීමට \\හෝ අමු නූල් භාවිතා කිරීමට අවශ්‍ය වනු ඇත r"foo\bar"):

from pathlib import Path

# .home() is new in 3.5, otherwise use os.path.expanduser('~')
directory_path = Path.home() / 'directory'
directory_path.mkdir()

file_path = directory_path / 'file'
file_path.touch()

සහ දැන්:

>>> file_path.is_file()
True

දැන් අපි ඒවා මකා දමමු. පළමුව ගොනුව:

>>> file_path.unlink()     # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False

බහු ලිපිගොනු ඉවත් කිරීමට අපට ග්ලෝබින් භාවිතා කළ හැකිය - පළමුව අපි මේ සඳහා ලිපිගොනු කිහිපයක් නිර්මාණය කරමු:

>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()

ඉන්පසු ගෝලීය රටාව හරහා නැවත කියන්න:

>>> for each_file_path in directory_path.glob('*.my'):
...     print(f'removing {each_file_path}')
...     each_file_path.unlink()
... 
removing ~/directory/foo.my
removing ~/directory/bar.my

දැන්, නාමාවලිය ඉවත් කිරීම නිරූපණය කිරීම:

>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False

අපට ඩිරෙක්ටරියක් සහ එහි ඇති සියල්ල ඉවත් කිරීමට අවශ්‍ය නම් කුමක් කළ යුතුද? මෙම භාවිතය සඳහා, භාවිතා කරන්නshutil.rmtree

අපගේ නාමාවලිය සහ ගොනුව ප්‍රතිනිර්මාණය කරමු:

file_path.parent.mkdir()
file_path.touch()

rmdirඑය හිස්ව ඇත්නම් මිස අසමත් වන බව සලකන්න , rmtree එතරම් පහසු වන්නේ එබැවිනි:

>>> directory_path.rmdir()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "~/anaconda3/lib/python3.6/pathlib.py", line 1270, in rmdir
    self._accessor.rmdir(self)
  File "~/anaconda3/lib/python3.6/pathlib.py", line 387, in wrapped
    return strfunc(str(pathobj), *args)
OSError: [Errno 39] Directory not empty: '/home/username/directory'

දැන්, rmtree ආනයනය කර නාමාවලිය funtion වෙත යොමු කරන්න:

from shutil import rmtree
rmtree(directory_path)      # remove everything 

සියල්ල ඉවත් කර ඇති බව අපට පෙනේ:

>>> directory_path.exists()
False

පයිතන් 2

ඔබ Python 2 හි සිටී නම්, pathlib2 නමින් pathlib මොඩියුලයේ පසුපෙළක් ඇත , එය නල මාර්ගයෙන් ස්ථාපනය කළ හැකිය:

$ pip install pathlib2

එවිට ඔබට පුස්තකාලය අන්වර්ථ කළ හැකිය pathlib

import pathlib2 as pathlib

නැතහොත් Pathවස්තුව කෙලින්ම ආනයනය කරන්න (මෙහි පෙන්වා ඇති පරිදි):

from pathlib2 import Path

එය ඕනෑවට වඩා නම්, ඔබට හෝ සමඟ ගොනු ඉවත් කළ හැකියos.removeos.unlink

from os import unlink, remove
from os.path import join, expanduser

remove(join(expanduser('~'), 'directory/file'))

හෝ

unlink(join(expanduser('~'), 'directory/file'))

ඔබට පහත නාමාවලි ඉවත් කළ හැකිය os.rmdir:

from os import rmdir

rmdir(join(expanduser('~'), 'directory'))

A ද ඇති බව සලකන්න os.removedirs- එය හිස් නාමාවලි පුනරාවර්තනයෙන් පමණක් ඉවත් කරයි, නමුත් එය ඔබගේ භාවිතයට ගැලපේ.


rmtree(directory_path)පයිතන් 3.6.6 හි ක්‍රියා කරන නමුත් පයිතන් 3.5.2 හි නොවේ - ඔබට rmtree(str(directory_path)))එහි අවශ්‍යය .
ස්ටයින්

4
import os

folder = '/Path/to/yourDir/'
fileList = os.listdir(folder)

for f in fileList:
    filePath = folder + '/'+f

    if os.path.isfile(filePath):
        os.remove(filePath)

    elif os.path.isdir(filePath):
        newFileList = os.listdir(filePath)
        for f1 in newFileList:
            insideFilePath = filePath + '/' + f1

            if os.path.isfile(insideFilePath):
                os.remove(insideFilePath)

1
මෙමඟින් ෆෝල්ඩරයේ ඇති ලිපිගොනු සහ ෆෝල්ඩරයේ ව්‍යුහය නොවෙනස්ව පවතින ෆෝල්ඩර පමණක් මකා දැමෙනු ඇත ..
ලලිතාෂ්

4

shutil.rmtree යනු අසමමුහුර්ත ශ්‍රිතයයි, එබැවින් එය සම්පූර්ණ වූ විට පරීක්ෂා කිරීමට ඔබට අවශ්‍ය නම්, ඔබට භාවිතා කළ හැකිය ... loop

import os
import shutil

shutil.rmtree(path)

while os.path.exists(path):
  pass

print('done')

1
shutil.rmtreeඅසමමුහුර්ත විය යුතු නොවේ. කෙසේ වෙතත්, එය වින්ඩෝස් මත වෛරස් ස්කෑනර් මැදිහත් වන බවක් පෙනෙන්නට තිබේ.
mhsmith

hmhsmith වෛරස් ස්කෑනර් ? එය වල් සමපේක්ෂනයක්ද, නැතහොත් ඒවා ඇත්ත වශයෙන්ම මෙම බලපෑම ඇති කළ හැකි බව ඔබ දන්නවාද? එසේ නම් එය පොළොවේ ක්‍රියාත්මක වන්නේ කෙසේද?
මාර්ක් අමරි

2

ගොනු මකා දැමීම සඳහා:

os.unlink(path, *, dir_fd=None)

හෝ

os.remove(path, *, dir_fd=None)

කාර්යයන් දෙකම අර්ථාන්විතව සමාන වේ. මෙම ශ්‍රිත මඟින් ගොනු මාර්ගය ඉවත් කරයි (මකා දමයි). මාර්ගය ගොනුවක් නොවන අතර එය නාමාවලිය නම්, ව්‍යතිරේකය මතු වේ.

ෆෝල්ඩර මකා දැමීම සඳහා:

shutil.rmtree(path, ignore_errors=False, onerror=None)

හෝ

os.rmdir(path, *, dir_fd=None)

සම්පූර්ණ නාමාවලි ගස් ඉවත් කිරීම සඳහා, shutil.rmtree()භාවිතා කළ හැකිය. os.rmdirඩිරෙක්ටරිය හිස්ව පවතින විට පමණක් ක්‍රියාත්මක වේ.

දෙමාපිය වෙත පුනරාවර්තන ලෙස ෆෝල්ඩර මකා දැමීම සඳහා:

os.removedirs(name)

යම් අන්තර්ගතයක් ඇති මවුපියන් වන තෙක් එය සෑම හිස් දෙමාපිය නාමාවලියක්ම ස්වයංක්‍රීයව ඉවත් කරයි

උදා. os.removedirs ('abc / xyz / pqr') නාමාවලි හිස් නම් 'abc / xyz / pqr', 'abc / xyz' සහ 'abc' ඇණවුමෙන් ඉවත් කරනු ඇත.

වැඩි තොරතුරු නිල ලේඛය පරීක්ෂා කිරීම සඳහා: os.unlink, os.remove, os.rmdir, shutil.rmtree,os.removedirs


1

ෆෝල්ඩරයේ ඇති සියලුම ගොනු ඉවත් කිරීමට

import os
import glob

files = glob.glob(os.path.join('path/to/folder/*'))
files = glob.glob(os.path.join('path/to/folder/*.csv')) // It will give all csv files in folder
for file in files:
    os.remove(file)

නාමාවලියක ඇති සියලුම ෆෝල්ඩර ඉවත් කිරීමට

from shutil import rmtree
import os

// os.path.join()  # current working directory.

for dirct in os.listdir(os.path.join('path/to/folder')):
    rmtree(os.path.join('path/to/folder',dirct))

0

එරික් අරුජෝගේ ප්‍රකාශය මගින් ඉස්මතු කර ඇති TOCTOU ගැටළුව වළක්වා ගැනීම සඳහා , නිවැරදි ක්‍රමය ඇමතීමට ඔබට ව්‍යතිරේකයක් අල්ලා ගත හැකිය:

def remove_file_or_dir(path: str) -> None:
    """ Remove a file or directory """
    try:
        shutil.rmtree(path)
    except NotADirectoryError:
        os.remove(path)

shutil.rmtree()ඩිරෙක්ටරි පමණක් ඉවත් කරන බැවින් os.remove()හෝ os.unlink()ගොනු පමණක් ඉවත් කරන බැවින්.


shutil.rmtree()නාමාවලිය පමණක් නොව එහි අන්තර්ගතයද ඉවත් කරයි.
ටියාගෝ මාටින්ස් පෙරෙස් 李大仁

-1

subprocessලස්සන හා කියවිය හැකි කේතයක් ලිවීම ඔබේ තේ කෝප්පය නම් භාවිතා කිරීමට මම නිර්දේශ කරමි :

import subprocess
subprocess.Popen("rm -r my_dir", shell=True)

ඔබ මෘදුකාංග ඉංජිනේරුවෙකු නොවේ නම්, සමහර විට ජුපිටර් භාවිතා කිරීම ගැන සලකා බලන්න; ඔබට සරලවම bash විධාන ටයිප් කළ හැකිය:

!rm -r my_dir

සාම්ප්‍රදායිකව, ඔබ භාවිතා කරන්නේ shutil:

import shutil
shutil.rmtree(my_dir) 

3
උපප්‍රොසෙස් වැළැක්වීම පුරුද්දකි
dlewin

3
මම මේ subprocessසඳහා නිර්දේශ නොකරමි . shutil.rmtreeකරන්නේ rm -rWindows මත වැඩ කිරීම සඳහා අමතර වාසියක් සමග, ගේ රැකියා දැන් හොදින්.
මාර්ක් අමරි
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.