How do I put a file path variable into pandas.read_csv?
Asked Answered
F

2

5

I tried to apply it through os.environ like so:

import os
import pandas as pd

os.environ["FILE"] = "File001"

df = pd.read_csv('/path/$FILErawdata.csv/')

But pandas doesn't recognize $FILE and instead gives me $FILErawdata.csv not found

Is there an alternative way to do this?

Flail answered 17/2, 2016 at 19:44 Comment(0)
S
8

New Answer:

If you like string interpolation, python now uses f-strings for string interpolation:

import os
import pandas as pd

filename = "File001"

df = pd.read_csv(f'/path/{filename}rawdata.csv/')

Old Answer:

Python doesn't use variables like shells scripts do. Variables don't get automatically inserted into strings.

To do this, you have to create a string with the variable inside.

Try this:

import os
import pandas as pd

filename = "File001"

df = pd.read_csv('/path/' + filename + 'rawdata.csv/')
Sidman answered 17/2, 2016 at 19:50 Comment(0)
S
1
df = pd.read_csv('/path/%(FILE)srawdata.csv' % os.environ)

I suspect you need to remove the trailing '/'.

Striker answered 18/2, 2016 at 4:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.