1

I want to open multiple files using a list of names and such that the names of the opened files will also incorporate the names in the list, as shown below:

List = ["Sin", "Cos", "Tan"]
for x in List:
    df_x = pd.read_csv("C:\\Users\\gtala\\OneDrive\\Desktop\\TIME AI\\NIST_Tests\\constants\\x.txt")

So I want x to replace x in the name of the file and in the directory, such that eventually I will open df_Sin from Sin.txt and df_Cos from Cos.txt, etc.

Thanks.

3 Answers 3

1
import pandas as pd
List = ["Sin", "Cos", "Tan"]
base="C:\\Users\\gtala\\OneDrive\\Desktop\\TIME AI\\NIST_Tests\\constants\\"
df = {}
for x in List:
    df[x] = pd.read_csv(base + x +".txt")

In the dictionary, df, above, the Sin variables are accessed using df['Sin'], for example, as follows:

print df['Sin']
Sign up to request clarification or add additional context in comments.

2 Comments

I like this, because i need the for loop to do operations on each data frame. However, the name of each df is not modified to include the names in the list. for example when I ask for df_Sin i get an error message that name "'df_Sin' is not defined"
Sure, I have modified the answer to use a dictionary that stores each result in 'Sin', 'Cos' and 'Tan' assignments.
1

map

f = "C:\\Users\\gtala\\OneDrive\\Desktop\\TIME AI\\NIST_Tests\\constants\\{}.txt".format
list(map(pd.read_csv, map(f, ["Sin", "Cos", 'Tan'])))

Comments

1

You may find it useful to store this in a dictionary data structure instead.

path = "C:\\Users\\gtala\\OneDrive\\Desktop\\TIME AI\\NIST_Tests\\constants"
file_names = ["Sin", "Cos", "Tan"]

df_dict = {f"df_{x}": pd.read_csv(f"{path}//{x}.txt") for x in file_names}

You can then access a dataframe of interest by using

df_dict['df_Sin']

3 Comments

This is the correct approach in my opinion. 2 suggestions to make it cleaner: Use the new string interpolation: f"df_{x}" rather than format (same with filepath) and save the directory path as a variable outside the dict to make it cleaner
So path = "C:\\Users\\gtala\\OneDrive\\Desktop\\TIME AI\\NIST_Tests\\constants" outside and then we have df_dict = {f"df_{x}: pd.read_csv(f"{path}//{x}.txt" for x in file_names}
Ah yeah that does looks nice. I haven't really used string interpolation before, thanks for pointing it out! You're more than welcome to edit if you like?

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.