0

is it possible to read csv file using string from another df?

normally, to read a csv file, i'd use the code as follow:

df = pd.read_csv("C:/Users/Desktop/file_name.csv")

however, i'd like to automate reading a csv file using string from another df:

df1_string = df1.iloc[0]['file_name']
df2 = pd.read_csv("C:/Users/Desktop/df1_string.csv")

i got a FileNotFoundError when i tried the above code: FileNotFoundError: [Errno 2] File b'C:/Users/Desktop/df1_string,csv' does not exist

kindly advices, many thanks

1 Answer 1

1

Use python string formatting:

df1_string = df1.iloc[0]['file_name']
df2 = pd.read_csv(f"C:/Users/Desktop/{df1_string }.csv")
Sign up to request clarification or add additional context in comments.

5 Comments

thank you for the response, could you provide an example of how it works if df1_string = apple
In that case it will create an empty dataframe with one column named as apple
i'm not sure whether i'm getting this right. but im trying to read(open) a cvs file in a folder. which df1 goes thru a function to generate the name of the file to be opened. In this case, the name of the file is 'apple'. however, the code you provide seems to be creating a new df instead.
Check the edited answer. is this what u want?
yeah, that's the one. sorry wasn't clear on my question. thanks

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.