I am trying to replace a string here in Python.
This is my Input -
link = (r"C:\dell\Documents\Ms\Realm")
I want my output to be like this:
C:/dell/Documents/Ms/Realm
I tried the replace method it didn't work.
the code tried:
link = (r"C:\dell\Documents\Ms\Realm")
link.replace("\","/")
In Python strings, the backslash "\" is a special character, also called the "escape" character. You need to add second backslash to "escape" it and use in string search.
link.replace("\\", "/")
There's nothing wrong with that Windows path. There's no reason to replace anything. A real improvement would be to use pathlib instead of raw strings:
from pathlib import Path
link = Path(r"C:\dell\Documents\Ms\Realm")
That would allow you to construct paths from parts using, eg joinpath, get the parts of the path with parts, the name with name, directory with parent etc.
var filePath=link.joinpath("some_file.txt")
print(filePath)
-------------------
C:\dell\Documents\Ms\Realm\some_file.txt
and more
>>> print(link.parts)
('C:\\', 'dell', 'Documents', 'Ms', 'Realm')
>>> print(link.parent)
C:\dell\Documents\Ms
Or search for files in a folder recursively:
var files=(for file in link.rglob("*.txt") if file.is_file())
Related
I have a given file path. For example, "C:\Users\cobyk\Downloads\GrassyPath.jpg". I would like to pull in a separate string, the image file name.
I'm assuming the best way to do that is to start from the back end of the string, find the final slash and then take the characters following that slash. Is there a method to do this already or will I have search through the string via a for loop, find the last slash myself, and then do the transferring manually?
The pathlib module makes it very easy to access individual parts of a file path like the final path component:
from pathlib import Path
image_path = Path(r"C:\Users\cobyk\Downloads\GrassyPath.jpg")
print(image_path.name) # -> GrassyPath.jpg
You can certainly search manually as you've suggested. However, the Python standard library already has, as you suspected, a function which does this for you.
import os
file_name = os.path.basename(r'C:\Users\cobyk\Downloads\GrassyPath.jpg')
I'm trying to open a file like this:
with open(str(script_path) + '\\description.xml', 'w+') as file:
where script_path is equal to this:
script_path = os.path.dirname(os.path.realpath(__file__)) + '\\.tmp')
When I run this I get an error that there is no such file or directory because when it tries to open the file it sees the whole path as a string, including the escape strings. Is there any way around this?
Obviously .replace() won't work here as it won't replace the escape string. Hoping there is a clever way to do this within the os module?
Not really sure why you're adding two backslashes. You can simply create the path using a single forward slash (Linux based) or backslash (win). Something like this:
script_path = os.path.dirname(os.path.realpath(__file__)) + '/tmp/description.xml'
However, better way to achieve this would be to use os.path.join as suggested by nomansland008.
>>> import os
>>> parent_dir = "xyz"
>>> dir = "foo"
>>> file_name = "bar.txt"
>>> os.path.join(parent_dir, dir, file_name)
'xyz/foo/bar.txt'
You won't have to bother about whether the string has slash(or not). It will be taken care by join.
In your case it can simply be:
os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tmp', 'description.xml')
Should work, provided the files and directories exist.
I know similar questions have been asked a few times on this site, but the solutions provided there did not work for me.
I need to rename files with titles such as
a.jpg
'b.jpg'
c.jpg
"d.jpg"
to
a.jpg
b.jpg
c.jpg
d.jpg
Some of these titles have quotation marks inside the title as well, but it doesn't matter whether they get removed or not.
I have tried
import os
import re
fnames = os.listdir('.')
for fname in fnames:
os.rename(fname, re.sub("\'", '', fname))
and
import os
for file in os.listdir("."):
os.rename(file, file.replace("\'", ""))
to then do the same for the " quotation mark as well, but the titles remained unchanged. I think it might be due to listdir returning the filenames with ' quotation marks around them, but I am not sure.
Edit: I am working on a Ubuntu 18.04.
On windows, a filename with double quotes in it isn't a valid filename. However, a filename with single quotes is valid.
A string with double quotes in it in python would look like:
'"I\'m a string with a double quote on each side"'
A string with single quotes in it in python would look like:
"'I\'m a string with a single quote on each side'"
Because you can't have a double-quote filename on windows, you can't os.rename('"example.txt"', "example.txt"). Because it can't exist to even be renamed.
You can put this script on your desktop and watch the filenames change as it executes:
import os
open("'ex'am'ple.t'xt'",'w')
input("Press enter to rename.")
#example with single quotes all over the filename
os.rename("'ex'am'ple.t'xt'", "example.txt")
open("'example.txt'",'w')
input("Press enter to rename.")
#example with single quotes on each side of filename
os.rename("'example2.txt'", "example2.txt")
Here is my attempt using a for-loop, like you do and list comprehension used on the string, which is also an iterable.
import os
files = os.listdir(os.getcwd())
for file in files:
new_name = ''.join([char for char in file if not char == '\''])
print(new_name)
os.rename(file, new_name)
Edit the forbidden_chars list with the characters, that you do not want in the future filename.
Remember that this will also change folder names afaik, so you may want to check at the start of the for-loop
if os.isfile(file):
before changing the name.
I actually do not understand how you would have filenames, that include the extension inside of quotation marks, but this should work either way. I highly recommend being careful if you want to remove dots.
I also recommend peeking at the documentation for the os module, before using its functions as they can do things you may not be aware of. For example: renaming to an existing filename within the directory will just silently replace the file.
I have a path to some file:
'home/user/directory/filename'
I want get the filename-subpart. The main problem is, I don't know the length of my string and I don't know the length of filename-subpart. I know just that filename is placed at the end of a string after the last slash /. The number of slashes in the string could be absolutely random (because I want get the filename from every directory on some PC).
Consequently I don't see for now the usual method with index extraction, like this:
string[number:]
Any ideas?
To get the basename use os.path.basename:
Return the base name of pathname path. This is the second element of the pair returned by passing path to the function split()
from os import path
pth = 'home/user/directory/filename'
print(path.basename(pth))
filename
Or str.rsplit:
print(pth.rsplit("/",1)[1])
filename
If you were trying to index a string from the last occurrence you would use rindex:
print(pth[pth.rindex("/") + 1:])
You could try this also,
>>> import os
>>> s = 'home/user/directory/filename'
>>> os.path.split(s)[1]
'filename'
I am Trying to add a custom path filed in my GUI but the problem is that when i use the command
cmds.fileDialog2(filemode=3,dialogStyle =1)
i get a file path like
C:\Users\anoorani\Desktop\Test
However Maya only seems to be reading paths like
C:/Users/anoorani/Desktop/Test
The backticks seem to be a problem
is there a way to replace "\" with "/" in python maya.....?
Acording to #ArgiriKotsaris note, you can use os.path.normpath(path):
Normalize a pathname by collapsing redundant separators and up-level references.
So that A//B, A/B/, A/./B and A/foo/../B all become A/B.
This string manipulation may change the meaning of a path that contains symbolic links.
On Windows, it converts forward slashes to backward slashes.
So your code be:
import maya.cmds as cmds
import os
path = cmds.fileDialog2(fm=3,dialogStyle =1)
path = path and os.path.normpath(path[0])
Or if you want to always using forward slashes, then no needs to os module and change last line to:
path = path and path[0].replace('\\', '/')
Note that name of file mode argument for fileDialog2 is fileMode or fm and not filemode.
Also fileDialog2 return a list of paths or None.