Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

auto_rename() can be optimized #37

Closed
zhbzhbzhbz opened this issue Aug 11, 2020 · 2 comments
Closed

auto_rename() can be optimized #37

zhbzhbzhbz opened this issue Aug 11, 2020 · 2 comments

Comments

@zhbzhbzhbz
Copy link

zhbzhbzhbz commented Aug 11, 2020

正好我的代码里也需要类似的功能,于是借鉴了一下,发现可能有个小bug,虽然一般不会出现。
比如现在文件夹里有1.jpg和1(2).jpg,然后还要下载1.jpg,那么如果用这种计算方式,算出的新文件名应该是1(2).jpg

flist = [f for f in os.listdir(fpath) if re.fullmatch(rf"{fname_no_ext}\(?\d*\)?{extension}", f)]

我自己的写法是从1(1).jpg、1(2).jpg……1(N).jpg开始遍历(可能先获取文件名列表,再在内存里判断会更快):

def auto_rename(file_path):
        if not os.path.exists(file_path):
            return file_path
        fpath, fname = os.path.split(file_path)
        fname_no_ext, ext = os.path.splitext(fname)
        for index in range(1,999):
            temp_path = fpath + os.sep + fname_no_ext + '(' + str(index) + ')' + ext
            if not os.path.exists(temp_path):
                return temp_path

然后我用chrome试了下,有1.jpg、1(2).jpg和1(3).jpg的情况下,再次下载1.jpg,它会跟我一样重命名为1(1).jpg

@zaxtyson
Copy link
Owner

已经改了,虽然是小概率,但是用户恰好删掉了之前下载的同名文件,就可能覆盖掉后面存在的文件。

def auto_rename(file_path) -> str:

刚刚还在纠结要不要加锁,试了一下,除非多个进程同时下载同名文件到同一个文件夹,且一堆网络请求下来时间间隔非常精妙才会出问题,想了想还是算了~

@zhbzhbzhbz
Copy link
Author

已经改了,虽然是小概率,但是用户恰好删掉了之前下载的同名文件,就可能覆盖掉后面存在的文件。

def auto_rename(file_path) -> str:

刚刚还在纠结要不要加锁,试了一下,除非多个进程同时下载同名文件到同一个文件夹,且一堆网络请求下来时间间隔非常精妙才会出问题,想了想还是算了~

嗯嗯~赞

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants