Python -- Quotations around filenames - python

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

Related

Why do some functions in Python change \ to \\

When I declare pass a file to shutil.copy as
shutil.copy(r'i:\myfile.txt', r'UNC to where I want it to go')
I get an error
No such file or directory 'i:\\myfile.txt'
I've experienced this problem before with the os module when I have a UNC path. Usually I just get frustrated enough that I forget using the os module and just put the file path into with open() or whatever I'm using it for.
It is my understanding that placing an r before '' is supposed to cause python to ignore escape characters and treat them as string literals, but the behavior I'm seeing leads me to believe that this is not the case. For some reason it takes the \ and changes it to \\.
I've seen this when using os.path.join where the \\ at the beginning of the the UNC Path gets turned into \\\\.
What is the best way to pass a string literal to ensure that all escape characters are ignored and the string is preserved?
Your string is not being modified by Python. It's the representation of your string that's coming out differently.
When the error is printed, Python calls repr() to print the value. This function will
Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a repr() method.
This can be very nice when debugging: if I paste that string (quotes, escapes, and all) into the REPL I'll get the string in memory that you were working with. I can use this to interactively try your copy command, maybe tweaking the string a bit.
If you want to see your string in a printed form, you could do
source_path = r'i:\myfile.txt'
target_path = r'UNC to where I want it to go'
print(f'Copying {source_path} to {target_path}...')
shutil.copy(source_path, target_path)

re.escape returns unusable directory

using re.escape() on this directory:
C:\Users\admin\code
Should theoratically return this, right?
C:\\Users\\admin\\code
However, what I actually get is this:
C\:\\Users\\admin\\code
Notice the backslash immediately after C. This makes the string unusable, and trying to use directory.replace('\', '') just bugs out Python because it can't deal with a single backslash string, and treats everything after it as string.
Any ideas?
Update
This was a dumb question :p
No it should not. It's help says "Escape all the characters in pattern except ASCII letters, numbers and '_'"
What you are reporting you are getting is after calling the print function on the resulting string. In console, if you type directory and press enter, it would give something like: C\\:\\\\Users\\\\admin\\\\code. When using directory.replace('\\','') it would replace all backslashes. For example: directory.replace('\\','x') gives Cx:xxUsersxxadminxxcode. What might work in this case is replacing both the backslash and colon with ':' i.e. directory.replace('\\:',':'). This will work.
However, I will suggest doing something else. A neat way to work with Windows directories in Python is to use forward slash. Python and the OS will work out a way to understand your paths with forward slashes. Further, if you aren't using absolute paths, as far as the paths are concerned, your code will be portable to Unix-style OSes.
It also seems to me that you are calling re.escape unnecessarily. If the printing the directory is giving you C:\Users\admin\code then it's a perfectly fine directory to use already. And you don't need to escape it. It's already done. If it wasn't escaped print('C:\Users\admin\code') would give something like C:\Usersdmin\code since \a has special meaning (beep).

How to Read A String Literal Stored in a Variable

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.

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.

Printing Parameter Values returning Unexpected Result, Python

I have the following python script snidbit:
inLines = sys.argv[0]
arcpy.AddMessage(inLines)
The input parameter is a multivalue input whereby the user can navigate to a file locations and choose multiple files as the input.
When I print out the variable, I get the follwoing:
Y:\2012_data\INFRASTRUCTURE.gdb\Buildings;'Z:\DATA FOR
2009\Base.gdb\CREEKS_UTM';'Z:\DATA FOR 2009\Base.gdb\LAKES_UTM'
Notice on the Z:drive, it is returning the path with single quotes around it, whereas the Y:drive does not. I believe this is caused by the spaces in the Z:drive paths. Is there a way to force the Z:drive paths to return without the quotes?
Thanks,
Mike
I managed to solve this issue. Python handles the parameters differently because of the path names. In the first parameter, there are no spaces in the file path. In the other 2 parameters, there are spaces. Python doesn't like spaces, so it forces the file path into a string value. I just wrote some code to override this.

Categories

Resources