简体   繁体   English

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

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

I just want to move a file from one folder to another (already know how to do that) and in the process check all the files in the destination folder and delete the files with the same name. 我只想将文件从一个文件夹移动到另一个文件夹(已经知道如何操作),并在此过程中检查目标文件夹中的所有文件并删除具有相同名称的文件。

I have two folders /src and /dst. 我有两个文件夹/ src和/ dst。

In folder /src I have: 在文件夹/ src中我有:

  • 'access.log.1.txt' 'access.log.1.txt'

and in folder /dst : 并在文件夹/ dst中:

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

When I move the file in /src to /dst I want to delete all the files named as the file in /src excluding the datetime() extension in the files of /dst. 当我将/ src中的文件移动到/ dst时,我想删除/ src中名为文件的所有文件,不包括/ dst文件中的datetime()扩展名。

So the /dst folder should look like this after the execution: 所以/ dst文件夹在执行后应如下所示:

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

This is the code I have to move files from /src to /dst: 这是我必须将文件从/ 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)

Anyone could help me? 有人可以帮帮我吗?

Thanks!! 谢谢!!

Sandip's answer should work, but if you specifically want it the way you've stated in your question, this could work: 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 "----------------------"

Note that this approach assumes that all your destination file names looks like they do in your question, ie that all of them have 4 periods ( . ) and that the datetime string is always between your third and fourth period. 请注意,此方法假定您的所有目标文件名都与您的问题相同,即所有目标文件名都有4个句点( . ),并且日期时间字符串始终位于第三个和第四个句点之间。

Remove all the file with a matching regex. 使用匹配的正则表达式删除所有文件。 Just navigate to destination folder and delete all files with your regex In your case use 只需导航到目标文件夹并使用正则表达式删除所有文件在您的案例中使用

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

It removes all the file with name access.log.1..txt Now, You can copy the file using 它删除名为access.log.1..txt的所有文件现在,您可以使用复制文件

cp filename.txt /dst/filename.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM