如果目标文件夹中已存在文件,如何替换?

Mig*_*uel 5 python file python-3.6

我只想将文件从一个文件夹移动到另一个文件夹(已经知道如何执行此操作),并在此过程中检查目标文件夹中的所有文件并删除同名的文件。

\n\n

我有两个文件夹 /src 和 /dst。

\n\n

在文件夹 /src 中我有:

\n\n
\n
    \n
  • \'access.log.1.txt\'
  • \n
\n
\n\n

并在文件夹 /dst 中:

\n\n
\n
    \n
  • \'access.log.1.20171110_115840565311.txt\'
  • \n
  • \'access.log.1.20171110_115940565311.txt\'
  • \n
  • \'access.log.2.20171110_115940565311.txt\'
  • \n
\n
\n\n

当我将 /src 中的文件移动到 /dst 时,我想删除 /src 中名为该文件的所有文件,不包括 /dst 文件中的 datetime() 扩展名。

\n\n

所以执行后 /dst 文件夹应该如下所示:

\n\n
\n
    \n
  • \'access.log.1.txt\'
  • \n
  • \'access.log.2.20171110_115940565311.txt\'
  • \n
\n
\n\n

这是我必须将文件从 /src 移动到 /dst 的代码:

\n\n
entrada = ENTRADA   #This 3 are the paths to the folders  /src\nsalida = SALIDA     #                                     /dst\nerror=ERROR         #                                     /err\nfiles=glob.glob(entrada)\nfor file in files:\n   fichero=open(file,encoding=\'utf-8\')\n   try:\n       for line in fichero:\n          la=line.replace("-","")\n          li=la.replace(\'\xe2\x80\x9d\'+chr(10),\'\')\n          li=li.split(\'"\')\n          line_DB(li)\n       fichero.close()\n       if TIME_RENAME==\'True\':\n          execution=str(datetime.now())\n          execution=execution.replace(\'.\',\'\')\n          execution=execution.replace(\'-\',\'\')\n          execution=execution.replace(\' \',\'_\')\n          execution_time=execution.replace(\':\',\'\')\n          base = os.path.splitext(file)[0]\n          base=base+\'.\'+execution_time+\'.txt\'\n          os.rename(file,base)\n          file=base\n       else:\n          print(\'Hello\')\n          #This is where I need the code\n\n       shutil.move(file, salida)\n       con.commit()\n   except:\n       logging.error(sys.exc_info())\n       print(sys.exc_info())\n       fichero.close()\n       shutil.move(file, error)\n
Run Code Online (Sandbox Code Playgroud)\n\n

有人可以帮助我吗?

\n\n

谢谢!!

\n

Pla*_*sma 2

桑迪普的答案应该有效,但如果您特别想要按照问题中所述的方式进行操作,则这可能有效:

import os

src_filename = "access.log.1.txt"
dst_dir = "test"

for filename in os.listdir(dst_dir):

    # Filter files based on number of . in filename
    if filename.count(".") < 4:
        continue

    # We need to remove the datetime extension before comparing with our filename
    filename_tokens = filename.split(".")  # List of words separated by . in the filename
    print "Tokens:", filename_tokens

    # Keep only indexes 0, 1, 2 and 4 (exclude index 3, which is the datetime-string)
    datetime_string = filename_tokens.pop(3)  # pop() also removes the datetime-string
    print "Datetime:", datetime_string
    dst_filename = ".".join(filename_tokens)
    print "Destination filename:", dst_filename

    # Check if the destination filename now matches our source filename
    if dst_filename == src_filename:
        # Get full path of file to be deleted
        filepath = os.path.join(dst_dir, filename)
        # Delete it
        print "Deleting:", filepath
        os.remove(filepath)
    print "----------------------"
Run Code Online (Sandbox Code Playgroud)

请注意,此方法假设所有目标文件名与您的问题中的名称相同,即所有文件名都有 4 个句点 ( .),并且日期时间字符串始终位于第三个和第四个句点之间。