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

How can I replace a file if already exists in the destination folder?

我只是想将一个文件从一个文件夹移动到另一个文件夹(已经知道该怎么做),并在此过程中检查目标文件夹中的所有文件并删除同名文件。

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

在文件夹 /src 中我有:

  • 'access.log.1.txt'

在文件夹 /dst 中:

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

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

所以 /dst 文件夹在执行后应该是这样的:

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

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

entrada = ENTRADA   #This 3 are the paths to the folders  /src
salida = SALIDA     #                                     /dst
error=ERROR         #                                     /err
files=glob.glob(entrada)
for file in files:
   fichero=open(file,encoding='utf-8')
   try:
       for line in fichero:
          la=line.replace("-","")
          li=la.replace('”'+chr(10),'')
          li=li.split('"')
          line_DB(li)
       fichero.close()
       if TIME_RENAME=='True':
          execution=str(datetime.now())
          execution=execution.replace('.','')
          execution=execution.replace('-','')
          execution=execution.replace(' ','_')
          execution_time=execution.replace(':','')
          base = os.path.splitext(file)[0]
          base=base+'.'+execution_time+'.txt'
          os.rename(file,base)
          file=base
       else:
          print('Hello')
          #This is where I need the code

       shutil.move(file, salida)
       con.commit()
   except:
       logging.error(sys.exc_info())
       print(sys.exc_info())
       fichero.close()
       shutil.move(file, error)

有人能帮帮我吗?

谢谢!!

删除所有具有匹配正则表达式的文件。 只需导航到目标文件夹并使用正则表达式删除所有文件 在你的情况下使用

rm access.log.1.[0-9,_]*.txt

它删除名称为 access.log.1..txt 的所有文件 现在,您可以使用

复制文件
cp filename.txt /dst/filename.txt

Sandip 的回答应该有效,但如果您特别希望按照您在问题中所述的方式进行回答,这可能有效:

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

请注意,此方法假定您的所有目标文件名看起来都与您的问题中的一样,即它们都有 4 个句点(.)并且日期时间字符串始终在您的第三个和第四期.