What is partial[1:] doing in this code [duplicate] - python

This question already has answers here:
Understanding slicing
(38 answers)
Closed 9 years ago.
I am new to python and trying to understand the _full_path from this example.
def _full_path(self, partial):
if partial.startswith("/"):
partial = partial[1:]
path = os.path.join(self.root, partial)
return path
What does the function do? Specifically, what does this line do?
partial = partial[1:]
It seems like some kind of list manipulation -- but I can't find syntax like that in this document.
What is the root property of self that is getting called?
Can somebody explain a little bit about what is happening in that code.

Because os.path.join will take later path start with '/' as base, try this:
print os.path.join('/a', '/b/')
it return '/b/', so you have to check and remove begin slash when you join path.
str is a sequence type, check here: http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange

That line drops the starting "/".
The function itself gives back the "full path".

Related

How to shorten a path (string) to just the file [duplicate]

This question already has answers here:
Extract file name from path, no matter what the os/path format
(22 answers)
Closed 3 years ago.
I'm currently making an autosave function for a program based in python, and I have very little knowledge of python. I remember learning how to cut, but this is a bit more of an advanced cut. Right now, I have it printing me the path file in string format (no I cannot use os.path or anything like that) and what I want, is for it to remove the entire path except for NAME.pse(The name will change as well). Here is an example path and ultimately what I'd like it to look like, but I would like for it to work with any path that it prints out so it has compatibility with anyone's computer in any file structure, along with any name of the session file (the .pse):
C:/Users/Install/OneDrive/B&BLab/Coding/TestingCell/PyMol.pse => PyMol.pse
You can use the split() function to split the string at all / characters. This will return a list, then just take the last element of that list:
myString = "C:/Users/Install/OneDrive/B&BLab/Coding/TestingCell/PyMol.pse"
myFile = myString.split('/')[-1]
However, Python does provide a function for this. Check out this answer.
If you want only the filename:
print("".join(stringa.split('/')[-1:]))
And if you want also the containing folder(s):
print("/".join(stringa.split('/')[-2:]))

Injecting environment variables to string path [duplicate]

This question already has answers here:
How to evaluate environment variables into a string in Python?
(3 answers)
Closed 2 years ago.
I have the following string :
some_string = "%envvar1%\location\execution.exe"
envvar1 is an environment variable with value of "c:\", and I would like some function as following:
some_string = "%envvar1%\location\execution.exe"
inject_env_variable(some_string)
print(some_string)
"c:\location\execution.exe"
Creating a function like this wouldnt be to difficult with regular expressions and os.environ but I was wondering if there was some kind of built in module that treats these kind of things.
Note: google searching anything with the word 'path' and 'python' is really tedious since all the searches are related to pythonpath :P
os.path.expandvars is probably what you are looking for. https://docs.python.org/3/library/os.path.html#os.path.expandvars
import os
def inject_env_variable(s):
return s.replace("%envvar1%", os.environ['envvar1'])
Should do the trick

How do I turn a list into a string [duplicate]

This question already has answers here:
Convert a list of characters into a string [duplicate]
(9 answers)
Closed 4 years ago.
I have written a code that ends up outputting what I want but in list format. Just to make it easier to understand, I will make up an input.
If I get
>>>
['H','e','l','l','o',' ','W','o','r','l','d']
as an output, how can I change it to:
>>>
'Hello World'
I have tried using .join() but it tells me that it does not work with lists as an error code.
If you need any more information, or I am being vague, just leave a comment saying so and I will update the question.
And if you leave a downvote, can you at least tell me why so that I can fix it or know what to improve for later posts
You join on the connector like this: ''.join(['H','e','l','l','o',' ','W','o','r','l','d'])
Just use join method by passing a list as parameter.
str = ''.join(['H','e','l','l','o',' ','W','o','r','l','d'])

Python Passing list by its name to a function [duplicate]

This question already has answers here:
How can I select a variable by (string) name?
(5 answers)
Closed 8 months ago.
names=['abcd','efgh']
nameoflist='names'
def(nameoflist=[]):
return nameoflist
I want to be able to return the entire list from the function
Assuming names is global as specified in the question, you can do this
names=['abcd','efgh']
nameoflist='names'
def return_names(nameoflist):
return globals()[nameoflist]
However, this is pretty ugly, and I'd probably try another way to do it. What do you need the name for? Is there any other way to get the information you're asking for?
This one way to do what you are asking. But it is not good programming.
names=['abcd','efgh']
def list_by_name(list_name):
return eval(list_name)
print(list_by_name('names'))
Also, argument list_name should be a string. It should not default to a list, which would make the function to fail if called without argument. It should not have a default value.

Checking if text file is empty Python [duplicate]

This question already has answers here:
How to check whether a file is empty or not
(11 answers)
Closed 6 years ago.
Is there a way to check if a text file is empty in Python WITHOUT using os ?
What I have tried so far
x = open("friends.txt")
friendsfile = x.readlines()
if friendsfile == None
But I don't think it's the correct way.
Not sure why you wouldn't use os, but I suppose if you really wanted you could open the file and get the first character.
with open('friends.txt') as friendsfile:
first = friendsfile.read(1)
if not first:
print('friendsfile is empty')
else:
#do something

Categories

Resources