[英]rename multiple files using glob with Python (file already exists)
I trying to rename multiple files inside a directory with Python, but the count inside for loop never update, so I get a "file already exists" error.我试图用 Python 重命名目录中的多个文件,但是 for 循环中的计数永远不会更新,所以我收到“文件已存在”错误。
How can I get an updated variable (i) so that the name of the file is never repeated?如何获取更新的变量 (i) 以使文件名不再重复?
def change_name():
for i, filename in enumerate(glob.glob(current_dir + '\packettest.txt')):
os.rename(filename, os.path.join(current_dir, 'packettest_sent' + str(i) + '.txt' ))
i = i + 1
This is the error that I get:这是我得到的错误:
os.rename(filename, os.path.join(current_dir, 'packettest_sent' + str(i) + '.txt' ))
WindowsError: [Error 183] Cannot create a file when that file already exists
EDIT:编辑:
Thanks to your comments, I understand what enumerate does, but the problem persist, i still equal 0. This is my full code:感谢您的评论,我了解 enumerate 的作用,但问题仍然存在,我仍然等于 0。这是我的完整代码:
import os.path
import sys
import glob
import time
current_dir = os.getcwd()
file_path = current_dir + "\packettest.txt"
#def main():
def change_name():
for i, filename in enumerate(glob.glob(current_dir + '\packettest.txt')):
os.rename(filename, os.path.join(current_dir, 'packettest_sent' + str(i) + '.txt' ))
def packet_listener():
while not os.path.exists(file_path):
time.sleep(1)
print "waiting..."
if os.path.isfile(file_path):
# read file
change_name()
time.sleep(1)
packet_listener()
print "OK"
else:
raise ValueError("%s isn't a file!" % file_path)
if __name__ == '__main__':
packet_listener()
Thanks for advance.感谢提前。
PS: sorry for my bad English PS:对不起我的英语不好
Below (avoid incrementing i since enumerate already does it)下面(避免增加 i 因为 enumerate 已经做到了)
def change_name():
for i, filename in enumerate(glob.glob(current_dir + '\packettest.txt')):
os.rename(filename, os.path.join(current_dir, 'packettest_sent' + str(i) + '.txt' ))
Please, replace this piece of code:请替换这段代码:
for i, filename in enumerate(glob.glob(current_dir + '\packettest.txt')):
os.rename(filename, os.path.join(current_dir, 'packettest_sent' + str(i) + '.txt' ))
with this:有了这个:
for i, filename in enumerate(glob.glob(current_dir + '\packettest.txt')):
new_name = os.path.join(current_dir, 'packettest_sent' + str(i) + '.txt' )
if os.path.isfile( new_name ) :
print( 'file exists:', new_name )
else :
os.rename(filename, new_name)
And please, think twice about this: enumerate(glob.glob(current_dir + '\packettest.txt'))
, what are trying to do?请三思而后行:
enumerate(glob.glob(current_dir + '\packettest.txt'))
,你想做什么? There's only one file, you don't use wildcards ( *
, etc), why you need a loop here and what results you re expecting?只有一个文件,您不使用通配符(
*
等),为什么在这里需要一个循环以及您期望什么结果?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.