My program currently gets a list of files from a directory and is supposed to move and rename them to another directory. Instead, it does file0 and file2, skipping file1. Here’s my code:
files = glob.glob("oldfiles/*")
print("Length ==", len(files))
print(files)
# Beginning files are... atext0.txt, atext1.txt, atext2.txt
for file in range(len(files) - 1): # I have to subtract one due to it skipping a file
newname = "ztext" + str(file) + ".txt"
redundantname = os.listdir("oldfiles")[file]
print(file)
print(redundantname)
shutil.move("oldfiles/" + redundantname, "newfiles/" + newname)
Output:
Length == 3
['oldfiles\\atext0.txt', 'oldfiles\\atext1.txt', 'oldfiles\\atext2.txt']
0
atext0.txt
1
atext2.txt
The files are renamed to ztext0 and 1.txt, but the original atext1.txt is left behind.
>Solution :
Can’t you just iterate through os.listdir("oldfiles") ?
i=0
for file in os.listdit("oldfiles"):
i+=1
...
and then you use i instead of the file variable that you use now