簡體   English   中英

將文件移動到恰好在Python中具有相同文件名的新文件夾中

[英]Move file to a new folder that happens to have the same file name in Python

在我的腳本中,很少遇到這個問題,因為我試圖將文件移動到這個新文件夾中,而這個新文件夾恰好有一個具有相同名稱的文件,但這只是發生了。 因此,我當前的代碼使用shutil.move方法,但是由於重復的文件名而出錯。 我希望我可以使用一個簡單的if語句來檢查源是否已在目標位置,並稍微更改名稱,但也無法進行該工作。 我在這里還閱讀了另一篇文章,該文章使用distutils模塊解決了此問題,但該帖子給了我一個屬性錯誤。 人們對此還有其他想法嗎?

我在下面添加了一些示例代碼。 在“ C:\\ data \\ new”目錄中已經有一個名為“ file.txt”的文件。 給出的錯誤是目標路徑已存在。

import shutil
myfile = r"C:\data\file.txt"
newpath = r"C:\data\new"
shutil.move(myfile, newpath)

您可以使用os.path.exists來檢查文件是否存在,然后刪除它(如果存在)。

import os
import shutil
myfile = r"C:\data\file.txt"
newpath = r"C:\data\new"
# if check existence of the new possible new path name.
check_existence = os.path.join(newpath, os.path.basename(myfile))
if os.path.exists(check_existence):
    os.remove(check_existence)
shutil.move(myfile, newpath)

在Python 3.4中,您可以嘗試pathlib模塊。 這只是一個示例,因此您可以將其重寫為更有效/使用變量:

import pathlib
import shutil

myfile = r"C:\data\file.txt"
newpath = r"C:\data\new"

p = pathlib.Path("C:\data\new")
if not p.exists():
   shutil.move(myfile, newpath)
#Use an else: here to handle your edge case.

暫無
暫無

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

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