user10085693
user10085693

Reputation: 1

Reading several input files in Python

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.

Upvotes: 0

Views: 58

Answers (2)

Vardan
Vardan

Reputation: 152

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.

Upvotes: 0

Brad
Brad

Reputation: 91

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

Upvotes: 2

Related Questions