首页 > 解决方案 > Assigning multi-line raw string to variable for use in read_csv

问题描述

I am trying to assign a raw file path to a variable for use in read_csv in python. The ultimate intent is to take file path as an input in a GUI, and use this to run read_csv. The string is very long, and, for the time being, I am just trying to get the string - variable assignment working.

I followed another thread which suggested using r'''drive:\yada\yada...''' however this adds an additional "\" to each step in the file path. Any suggestions for how to prevent this? Also, any suggestions on best approach to take a file path as input to a GUI and use this to read_csv would be greatly appreciated.

Example of problem below...

In[219]: pathProject = r'''C:\Users\Account\OneDrive\
\Documents\Projects\2016\Shared\
\Project-1\Administrative\Phase-1\
\Final'''

In[220]: pathProject
Out[220]: 'C:\\Users\\Account\\OneDrive\\\n\\Documents\\Projects\\2016\\Shared\\\n\\Project-1\\Administrative\\Phase-1\\\n\\Final'

标签: python

解决方案


如果您想通过将长字符串拆分为多行来输入一个长字符串,您可以利用 Python 的字符串连接。由于您想在多行中输入它,它们必须包含在括号中,例如:

pathProject = (r"C:\Users\Account\OneDrive"
    r"\Documents\Projects\2016\Shared"
    r"\Project-1\Administrative\Phase-1"
    r"\Final")

print(pathProject)
# C:\Users\Account\OneDrive\Documents\Projects\2016\Shared\Project-1\Administrative\Phase-1\Final

请注意左括号和右括号,并且必须将字符串的每个部分声明为原始字符串。


推荐阅读