Home > Enterprise >  Merge Multiple excel file
Merge Multiple excel file

Time:07-30

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:\ok\data")  
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')

CodePudding user response:

I expect this to work for you:

import os
import pandas as pd
cwd = os.getcwd() 
dir_name = 'D:\ok\data'
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')

CodePudding user response:

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')

CodePudding user response:

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.

  • Related