How to Read A String Literal Stored in a Variable - python

I was wondering if there was a way to read a string literal stored in a variable. I was essentially trying to extract the file name for a variable containing a file path. I'm aware that you need to place r' before the path name. In my example below, the variable I'm trying to update is 'test'. So basically I'm unaware of how I can use r' on the variable name to avoid parts of the path being read as unicode characters. Is there a way to do this?
test='NAI\site_summaries\410_-_407_Central'
head,tail=os.path.split(test)
print(tail)
The code above returns 'site_summaries_-_407_Central', where it should be returning '410_-_407_Central'. Please keep in mind that I have a variable containing a list of these paths but I just chose to show one path for the sake of simplicity.

Related

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?
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.

Python string format

I have defined the string variable
value=“c:/program files/tm su/usr”
I need to use this variable in another string like
Bashcmd=“Override project={value}”
I tried adding the rf option like this
Bashcmd =rf“Override {value}”
But it’s printing only until c:/program, white spaces are neglected.
Is there any way to use entire path in Bashcmd and can’t remove spaces in directory path because many system share same paths.
You can format strings like this:
value="c:/program files/tm su/usr"
Bashcmd=f"Override project=\"{value}\""
or you can simply concatenate the string like this:
Bashcmd="Override project=\""+value+"\""

Python String Slicing from known word in string

I'm trying to read a variable which is written by another function (outside of my control), to look for the presence of a known word and then to copy a sub string beginning at the known word and ending either at the end of the line or a | delimiter.
So I want to write to this variable based on a simple if statement I've written, but at the moment it doesn't take any consideration of what is already in the variable and it needs to. As the code I'm writing makes use of all sorts of aliases, I've tried to simplify what I am doing below
So, firstly the variable 'devices' is written to elsewhere but available to me.
I'm reading another variable 'area' which if specifically set to '3', I need to write the variable 'devices' with the string of 'box2|box3' (or 'box3|box2' - it doesn't matter) and I can ignore the existing content of 'devices' UNLESS it contains 'box1' in the string. It may appear anywhere within the string and will also be appended by other data, but it always either finishes at the end of the line, OR by a | delimiter. So I need to read the entire variable, look for the presence of 'box1' and read as many characters into another variable up until the end of the line of it hits the | delimiter.
The only code I can really share here is this:
area = "3"
if area == "3":
devices = "box2|box3"
print devices
Let's say that 'devices' contains 'box5|box6_standard|box9|box8_ex_345|box1_182', I need to extra box1_182 from that string (and append it back in when I write 'devices' variable - I don't need to worry about any other pre-existing content of that variable.
As another example, the existing 'devices' variable may contain 'box7|box1_345|box6|box8_ex_345', in this case, I'd need to take 'box1_345' and append it to the devices string before I write 'box2|box3' to it ('box2|box3|box1_182')
I'd use regex and the in word to check if devices has 'box1'. If so then simply append it to the new devices string
import re
devices='box5|box6_standard|box9|box8_ex_345|box1_182'
area = "3"
if area == "3":
tdevices = "box2|box3"
if 'box1' in devices:
t=re.search('box1[0-9_:a-zA-Z]*', devices)
devices=tdevices+'|'+t.group()
else:
devices=tdevices
print devices

Getting (and appending) correct file path in Python 2.7

I have a previously defined file name in a string format, and a previously defined variable called value. I am trying to store a variable that looks like:
C:\Users\Me\Desktop\Value_Validation_Report
with the syntax below, I instead get:
C:\Users\Me\Desktop\Value\ _Validation_Report
target_dir= os.path.dirname(os.path.realpath(FileName))
ValidationReport=os.path.join(target_dir,value,"_Validation_Report")
print ValidationReport
Every other combination I have tried leads to an error. Any help would be greatly appreciated!
If value is a String, you must concatenate that with "_Validation_Report
target_dir= os.path.dirname(os.path.realpath(FileName))
ValidationReport=os.path.join(target_dir,value + "_Validation_Report")
print ValidationReport
os.path.join will add a separator (which depends on the operating system) between each string you give it. To avoid this, simply put your value and "_Validation_Report" strings together as one String. See more about os.path.join.

Python -- Quotations around filenames

I'm not quite sure when I need to put quotations around the filenames in Python.
For example, when I set
f = open(file)
I can run something like
len(f.read())
and it will run fine.
However, when I do it directly, it only works with
len(open("file").read())
Likewise, in terminal when running from Python I always have to use quotations.
What is the 'rule' when using quotations?
Thank you.
In python you can always use the name of a variable or function outside quotations, but the name of a file is usually not a variable.
If file is the name of a string variable you can always do open(file).read(), however if it is literally the filename you must always do open("file").read().
Quotations indicate a string literal constant. No quotations indicate that you're referencing a variable, which may itself be a string (in this case, populated with the path to a file).

Categories

Resources