Search code examples
pythondirectoryfile-conversionfile-not-foundos.path

Can't find file - FileNotFoundError: [Errno 2] No such file or directory


my code looks like this:

import os
from os import listdir
from os.path import isfile, join
import pyexcel as p

rootdir = r'C:/Users/aleks/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        if file.endswith('.xls'):
            new_file = p.save_book_as(file_name=file, dest_file_name=file.split('.')[0]+ '.xlsx')
            os.remove(file)
        else:
            continue

Now I know that this part works fine as it returns exactly what I want:

rootdir = r'C:\Users\aleks\Desktop\test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print(file)

Files are correctly listed after using print(file), but i can't convert them to xlsx as there is an error showing up: FileNotFoundError: [Errno 2] No such file or directory: 'file1.xls'. Which I find weird because I can clearly see the files after using print(file)

To clarify, in rootdir there are directories which contain .xls files that have to be converted into.xlsx


Solution

  • Try below code. I guess the problem is that you try to delete files in sub_directory that are different from your Python root.

    for root, dirs, files in os.walk(rootdir):
        for name in files:
            if name.endswith('.xls'):
                fname = os.path.join(root, name)
                new_file = p.save_book_as(file_name=fname, dest_file_name=os.path.join(root, fname.split('.')[0]+ '.xlsx'))
                os.remove(fname)