我正在尝试使用python 3.7.3重命名我的一个文件夹中的一堆文件,并且不会重命名其中带有“复制”一词的文件。重命名后重命名!!
我以为是因为它们中有空格,连字符或字母,所以我在其他文件的名称中添加了一些名称,但确实重命名了它们。例如:它将重命名:
'10 60'
'54 - 05'
'9200 d'
Run Code Online (Sandbox Code Playgroud)
但不会重命名:
'7527复制'
这是我开始使用的文件名之一,它不会重命名(只是要特别清楚):
'6576348885058201279439757037938886093203209992672224485458953892 - Copy'
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
import os
from random import randint
def how_many_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
directory = os.listdir(os.getcwd())
for i in directory:
if not "py" in i: #so it won't rename this file
os.rename(i, str(how_many_digits(4)) + str(os.path.splitext(i)[1]))
for i in directory:
print(i) #why does this print the old names instead of the new ones?!!
Run Code Online (Sandbox Code Playgroud)
编辑:这是我在这里的第一个问题,我不知道我在做什么,所以请耐心等待
khe*_*ood 12
Copy由于以下检查,它不会使用名称重命名文件:
if not "py" in i: #so it won't rename this file
Run Code Online (Sandbox Code Playgroud)
如果Copy在名称中,则py在名称中。
也许你应该有
if not i.endswith('.py'):
Run Code Online (Sandbox Code Playgroud)
代替。
如果要更新的目录列表,则必须listdir再次呼叫。
directory = os.listdir(os.getcwd()) # get updated contents
for i in directory:
print(i)
Run Code Online (Sandbox Code Playgroud)
您只分配directory一次。您需要listdir再次致电来更新它。
directory = os.listdir(os.getcwd())
for i in directory:
if not "py" in i: #so it won't rename this file
os.rename(i, str(how_many_digits(4)) + str(os.path.splitext(i)[1]))
updated_directory = os.listdir(os.getcwd()) # NEW
for i in updated_directory:
print(i) #why does this print the old names instead of the new ones?!!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
203 次 |
| 最近记录: |