Search code examples
pythonpandascsvimport

How to create variables for substitution based on user for unique filepath in python?


I'm writing code that I want to make generic to whoever needs to follow it. Part of the code is reading in an excel file that the user has to download. I know that each user has a specific 6-digit unique ID, and the folder and name of the file remains the same. Is there some way for me to modify the pd.read_csv function so that it is like this:

USERID = '123abc'
pd.read_csv(r'C:\Users\USERID\Documents\Dataset.csv') 

I keep getting stuck because there is an ' next to the r so concatenation with a constant does not seem to work.

Similarly, is there a method for code for exporting that would insert the current date in the title?


Solution

  • What you want to use are formatted strings. The r preceding the string literal in your code denotes that you are creating a raw string, which means that you aren't going to ever see the value of your variable get assigned correctly within that string. Python's docs explain what these raw strings are:

    Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters. (3.10.4 Python Language Reference, Lexical Analysis)

    Like Fredericka mentions in her comment, the formatted string is a great way to accomplish what you're trying to do. If you're using Python version 3.6 or greater, you can also use the format method on the string, which does the same thing.

    # set the User ID
    user_id = "PythonUser1"
    
    # print the full filepath
    print("C:\\Users\\{}\\Documents\\Dataset.csv".format(user_id))
    
    # read the CSV file using formatted string literals
    my_csv = pd.read_csv("C:\\Users\\{user_id}\\Documents\\Dataset.csv")
    
    # read the CSV file using the format method
    my_csv = pd.read_csv("C:\\Users\\{}\\Documents\\Dataset.csv".format(user_id))
    

    For more information, I'd recommend checking out the official Python docs on input and output.