簡體   English   中英

使用Python將某些文件復制到其他文件夾(Python中的文件管理)

[英]Copy certain files to other folder using Python ( File Management in Python )

如果存在某個文件,我想檢查文件夾和所有子文件夾。 如果存在,那么我想將其復制到另一個文件夾中。 我試過以下的東西

def copy_files(src, dest):
    files = os.listdir(src)
    for f in files:
        shutil.copy(src +f , dest)

for root, dirs, files in os.walk(my_path):
    for f in files:
        if f.endswith(".7z"):
            print("found files: " , f)
            copy_files(my_path, arch_dest)

在copy_files函數上工作。 但它在循環內部不起作用。

我收到以下錯誤:

權限被拒絕:'。/ data / f_1'

我究竟做錯了什么?

復制功能適用於其他文件夾。 但在這個循環中,它不起作用。 我需要讓它在循環中工作。

更新:

我假設問題更多的是路徑,我已經在for循環中檢查了它顯示的主目錄。 with print(os.getcwd())

檢查文件時是否需要轉到文件夾?

最后找到了解決方案。 我知道它是因為Root / Path。 它與admin/sudo東西無關。

它可以如下完成。

for r,d,files in os.walk(my_path):
    for f in files:
        print(r)
        shutil.copy(r + "/" + f, dest_path)

嘗試在循環周圍使用try / except忽略您沒有搜索權限的文件:

try:
    for root, dirs, files in os.walk(my_path):
        for f in files:
            if f.endswith(".7z"):
                print("found files: " , f)
                copy_files(my_path, arch_dest)
except OSError:
    pass

您需要以sudo用戶身份運行python腳本

e.g. sudo python filename.py

暫無
暫無

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

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