0

I have several Excel files that I would like to read in with my code. Instead of using the following command with the explicit file name:

df = read_excel("a.xlsx",sheet_name=0)

I would like to list all of my Excel file names in a .txt file (like data.txt) and then read data.txt line by line to store each Excel file name in a variable: i.e. after reading the first line of data.txt which is a.xlsx, I will assign

var1 = a.xlsx

My question is how do I open a.xlsx afterwards.

df = read_excel(var1,sheet_name=0) 

does not work. Is there a way to open Excel files without having their names explicitly written out in Python? Thanks in advance.

6
  • Are you using pandas? Commented Jul 18, 2018 at 23:20
  • 1
    var1 = a.xlsx is not valid python unless a.xlsx exists. That's probably not what you want. You want var1 = 'a.xlsx'. Commented Jul 18, 2018 at 23:21
  • What do you mean by does not work? What error do you get? Commented Jul 18, 2018 at 23:25
  • Yes, I am using pandas. Commented Jul 18, 2018 at 23:27
  • The error is: No such file or directory: '"a.xlsx"\r\n' Commented Jul 18, 2018 at 23:28

2 Answers 2

2

You need to do var1.rstrip() to remove \n.

Sign up to request clarification or add additional context in comments.

Comments

0

Assume that you text file is like this new.txt remove the quotes ("") from the text file. you completely misunderstood the comments.

a.xlsx
b.xlsx
c.xlsx

your code should be something like this:

file = open("new.txt")
for var in file:
    df = read_excel(var.strip(),sheet_name=0) // reading the files one by one
    // Do some processing

This just a skelton. You are getting that error is because there are some extra characters when reading the file (\r\n). The strip function would remove those characters and any white spaces.

2 Comments

and it still says IOError: [Errno 2] No such file or directory:
However wen I write a.xlsx directly in read_excel command (and I am not using var1) it works and does not complain with no such file or directory.

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.