1

I'm almost done with merging excel files with pandas in python but when I give the path it wont work. I get the error ''No such file or directory: 'file1.xlsx'''. When I leave the path empty it work but I want to decide from what folder it should take files from. AND I saved the file the folder 'excel'

cwd = os.path.abspath('/Users/Viktor/downloads/excel') #If i leave it empty and have files in /Viktor it works but I have the desired excel files in /excel 

print(cwd)
files = os.listdir(cwd)  
df = pd.DataFrame()
for file in files:
   if file.endswith('.xlsx'):
       df = df.append(pd.read_excel(file), ignore_index=True) 
df.head() 
df.to_excel(r'/Users/Viktor/Downloads/excel/resultat/merged.xlsx')
0

3 Answers 3

2

pd.read_excel(file) looks for the file relative to the path where the script is executed. If you execute in '/Users/Viktor/' try with:

import os
import pandas as pd

cwd = os.path.abspath('/Users/Viktor/downloads/excel') #If i leave it empty and have files in /Viktor it works but I have the desired excel files in /excel 

#print(cwd)
files = os.listdir(cwd)  


df = pd.DataFrame()
for file in files:
   if file.endswith('.xlsx'):
       df = df.append(pd.read_excel('downloads/excel/' + file), ignore_index=True) 
df.head() 
df.to_excel(r'/Users/Viktor/downloads/excel/resultat/merged.xlsx')
Sign up to request clarification or add additional context in comments.

Comments

1

How about actually changing the current working directory with

os.chdir(cwd)

Just printing the path doesn't help.

Comments

1
from pathlib import Path
import pandas as pd

# path to files
p = Path('/Users/Viktor/downloads/excel')

# find the xlsx files
files = p.glob('*.xlsx')

# create the dataframe 
df = pd.concat([pd.read_excel(file, ignore_index=True) for file in files])

# save the file
df.to_excel(r'/Users/Viktor/Downloads/excel/resultat/merged.xlsx')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.