Reputation: 23
Hi I am very new to Python and trying to read files with same name in two different folders. creating dataframes per new_name_file is tedious. How to optimize the code.
Example Code: to read team_ABC.txt in differnt folders
df1 = pd.read_csv(r'C:\Users\2020\team_ABC.txt',sep='\t')
df2 = pd.read_csv(r'C:\Users\2021\team_ABC.txt',sep='\t')
Example Code: to read team_XYZ.txt in differnt folders
df3 = pd.read_csv(r'C:\Users\2020\team_XYZ.txt',sep='\t')
df4 = pd.read_csv(r'C:\Users\2021\team_XYZ.txt',sep='\t')
I want to read same named files from folder 2020 with folder 2021. is there a way in which I can achieve it in more optimized manner like:
df1 = pd.read_csv(r'C:\Users\2020\team_{same_name}.txt',sep='\t')
df2 = pd.read_csv(r'C:\Users\2021\team_{same_name}.txt',sep='\t')
Upvotes: 0
Views: 422
Reputation: 998
Do you mean something like this?
import os
def read_csv_file(team_name):
base_path = "C:/Users/"
df2020 = pd.read_csv(os.path.join(base_path, "2020", f"team_{team_name}.txt"), sep='\t')
df2021 = pd.read_csv(os.path.join(base_path, "2021", f"team_{team_name}.txt"), sep='\t')
return df2020, df2021
df1, df2 = read_csv_file("XYZ")
Upvotes: 1
Reputation:
if your current working directory is the 2020 folder you can use the ../ command and it will look something like this
../2021+filename
Upvotes: 1