Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

os.listdir() skips a file in a list

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading