hernanavella hernanavella - 17 days ago 5
Python Question

How can I use a loop to import files to pandas?

I have several .txt files that I need to import to work in pandas, given a specific condition. Right now I do the same procedure for each one. I want to do it using a for-loop.This is what I have tried:

Each key is asociated with a different .txt file

All files are in same folder

filenames = ['a', 'b', 'c', 'd', 'e']

for i in filenames:
if name == i:
location = r'C:\Users\Folder\ + 'i'.txt'


What is the correct syntax to write that location path so that it can be used in a loop?

Thanks

Answer

Try to concatenate the strings this way:

location = 'C:\\Users\\Folder\\' + i + '.txt'