Merge Multiple excel file

Question:

I am trying to merge excel file but getting error FileNotFoundError: [Errno 2] No such file or directory: 'link110.xlsx'

import os
import pandas as pd
cwd = os.getcwd() 
files = os.listdir("D:okdata")  
df = pd.DataFrame()
for file in files:
    df = df.append(pd.read_excel(file), ignore_index=True) 
    df.head() 
    df.to_excel('Combined_Excels.xlsx')
Asked By: Amen Aziz

||

Answers:

When you read files you can use either an absolute path, or a relative path. In your code, you try to use a relative path but your current working directory isn’t the same as the directory with the excel files.

There’s a bit shortage of information but it may work:

for file in files:
    df = df.append(pd.read_excel("D:/ok/data/" + file), ignore_index=True) 
    df.head() 
    df.to_excel('Combined_Excels.xlsx')

Also, you overwrite file ‘Combined_Excels.xlsx’ every itertation. To avoid this you can do something like this:

import os
import pandas as pd
files = os.listdir("D:/ok/data")  
df = pd.DataFrame()
for file in files:
    df_read = pd.read_excel("D:/ok/data/" + file), ignore_index=True)
    df = pd.concat((df, df_read), axis=0) 
df.to_excel('Combined_Excels.xlsx')
Answered By: Kirill Safonov

I believe it is because there is no file in your current working directory called link110.xlsx. You will need to provide the absolute path, rather than the relative path.

Answered By: Mouse

I expect this to work for you:

import os
import pandas as pd
cwd = os.getcwd() 
dir_name = 'D:okdata'
files = [os.path.join(dir_name, x) for x in os.listdir(dir_name) if x.endswith('.xlsx')]  
df = pd.DataFrame()
for file in files:
    df = pd.concat([df, pd.read_excel(os.path.join(dir_name, file))])
    df.to_excel('Combined_Excels.xlsx')
Answered By: René
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.