如果文件存在,则删除文件 [英] If file exists then delete the file

查看:339
本文介绍了如果文件存在,则删除文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于重命名文件的vbscript.我需要在脚本中实施的操作是删除新文件"(如果已存在).

I have a vbscript that is used to rename files. What I need to implement into the script is something that deletes the "new file" if it already exists.

例如:我有一批文件的命名如下:11111111.dddddddd.pdf,其中文件被重命名为11111111.pdf.问题是,当我重命名为11111111.pdf格式时,我以重复的文件结尾,然后使脚本失败,因为您显然无法拥有2个同名文件.我需要它来重命名第一个,但随后删除其他被重命名为相同的名称.

For example: I have a batch of files that are named like this 11111111.dddddddd.pdf where the files get renamed to 11111111.pdf. The problem is that when I rename to the 11111111.pdf format I end of with files that are duplicated and then makes the script fail because you obviously cant have 2 files with the same name. I need it to rename the first one but then delete the others that are renamed the same.

到目前为止,这是我到目前为止对IF语句所拥有的内容,但是它不起作用,并且出现错误消息,提示类型不匹配:'FileExists".我不确定如何获得这部分代码以执行我想要的方式.任何帮助或建议,将不胜感激.

Here is what I have so far for my IF statement but it doesnt work and I get and error that says "Type mismatch: 'FileExists". I am not sure how to get this part of the code to execute the way I would like. Any help or suggestions would be greatly appreciated.

dim infolder: set infolder = fso.GetFolder(IN_PATH)
dim file
for each file in infolder.files

dim name: name = file.name
dim parts: parts = split(name, ".")
dim acct_, date_
acct_ = parts(0)
date_ = parts(1)


' file format of a.c.pdf
if UBound(parts) = 2 then
    ' rebuild the name with the 0th and 2nd elements
    dim newname: newname = acct_ & "." & parts(2)
    ' use the move() method to effect the rename
    file.move fso.buildpath(OUT_PATH, newname)  

    if  newname = FileExists(file.name) Then            
    newname.DeleteFile()
    end if   
end if

next 'file

推荐答案

您已经关闭了,您只需要删除文件之前尝试覆盖它即可.

You're close, you just need to delete the file before trying to over-write it.

dim infolder: set infolder = fso.GetFolder(IN_PATH)
dim file: for each file in infolder.Files

    dim name: name = file.name
    dim parts: parts = split(name, ".")

    if UBound(parts) = 2 then

       ' file name like a.c.pdf    

        dim newname: newname = parts(0) & "." & parts(2)
        dim newpath: newpath = fso.BuildPath(OUT_PATH, newname)

        ' warning:
        ' if we have source files C:\IN_PATH\ABC.01.PDF, C:\IN_PATH\ABC.02.PDF, ...
        ' only one of them will be saved as D:\OUT_PATH\ABC.PDF

        if fso.FileExists(newpath) then
            fso.DeleteFile newpath
        end if

        file.Move newpath

    end if

next

这篇关于如果文件存在,则删除文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆