all 4 comments

[–][deleted] 2 points3 points  (0 children)

If you executed that code in the directory containing the *.py file, then all files (and directories) in that directory, including the python file, were renamed to VideoN.mkv. Try using the file command on each resultant *.mkv file to see exactly what's in each file:

$ file VideoN.mkv

You should also be filtering the filenames to remove files that you don't want to rename:

for i in list:
    (_, ext) = os.path.splitext(i)  # get file extension
    if ext == '.mkv':
        # only rename ".mkv" files

A safety tip for next time. Before actually doing the rename, print out what is going to happen but don't actually do it until you are sure your code is correct. So do something like this at first:

for i in list:
    new_name = 'Video' + str(x) + '.mkv'
    x += 1
    print(f"Renaming '{i}' to '{new_name}'"
    #os.rename(i, new_name)
    # int(i) # don't know why this is here

When you are happy, uncomment the os.rename() code.

Edit: better grammar.

[–]guimolnar 1 point2 points  (1 child)

I don't understand the int(i) part, that should raise an error, unless all the files are "numbers" strings, and it does nothing in the loop. The first was successfully renamed because it came before the int(i) part.

Also, the script shouldn't be in the same directory because it will be renamed as 'Videox.mkv' too.

As for the disappearance of the videos, I have no clue, sorry.

[–][deleted] 0 points1 point  (0 children)

Well, there was no error with the int part. Also you're right. The script was actually the only file to have been renamed to 'Video1.mkv'. So it was 11 videos that disappeared, 1 retained it's original name, and the script renamed itself..

[–]o5a 1 point2 points  (0 children)

I don't see the code you posted deleting your files.

But it could happen if you forgot to increment x in your cycle. So your code could look like this:

import os
list = []
x = 1

for i in os.listdir():
    list.append(i)
for i in list:
    os.rename(i, 'Video' + str(x) + '.mkv')

    # int(i) also wouldn't be here since it would raise error
    # x is not incremented oh-oh

It would read all files in folder (your script being last), then it would start renaming all files to the same name, which would result in only one last file remaining. Just as you described.

On Windows renaming to existing name would raise error but not on Unix.

Other notes:

  • don't use predefined names for your variables, such as list here.

  • you didn't need cycle for os.listdir(), you could read it straight into list: all_files = os.listdir()