adding string in others - python

I have a string like script = "C:\Users\dell\byteyears.py". I wanna put the string "Python27\" in between the string like script = "C:\Users\dell\Python27\byteyears.py. Why I need is because build_scripts is not running correctly on the windows. Anyway, how can I do this wish in time efficient way ?
EDIT : I will not print anything. String is stored on the script variable in the build_scripts
script = convert_path(script)
I should put something to convert it, like
script = convert_path(script.something("Python27/"))
The question is that what something should be.

os.path is best for dealing with paths, also forward slashes are ok to use in Python.
In [714]: script = r"C:/Users/dell/byteyears.py"
In [715]: head, tail = os.path.split(script)
In [716]: os.path.join(head, 'Python27', tail)
Out[716]: 'C:/Users/dell/Python27/byteyears.py'
in a module.
import os
script = r"C:/Users/dell/byteyears.py"
head, tail = os.path.split(script)
newpath = os.path.join(head, 'Python27', tail)
print newpath
gives
'C:/Users/dell/Python27/byteyears.py'
internally Python is in general agnostic about the slashes, so use forward slashes "/" as they look nicer and save having to escape.

import os
os.path.join(script[:script.rfind('\\')],'Python27',script[script.rfind('\\'):])

Try:
from os.path import abspath
script = "C:\\Users\\dell\\byteyears.py"
script = abspath(script.replace('dell\\', 'dell\\Python27\\'))
Note: Never forget to escape \ when working with strings!
And if you're mixing / and \ then you'd better use abspath() to correct it to your platform!
Other ways:
print "C:\\Users\\dell\\%s\\byteyears.py" % "Python27"
or if you want the path to be more dynamic, this way you can pass a empty string:
print "C:\\Users\\dell%s\\byeyears.py" % "\\Python27"
Also possible:
x = "C:\\Users\\dell%s\\byeyears.py"
print x
x = x % "\\Python27"
print x

Related

Altering Windows file paths so that they use '/' instead of '\' [duplicate]

I am working in python and I need to convert this:
C:\folderA\folderB to C:/folderA/folderB
I have three approaches:
dir = s.replace('\\','/')
dir = os.path.normpath(s)
dir = os.path.normcase(s)
In each scenario the output has been
C:folderAfolderB
I'm not sure what I am doing wrong, any suggestions?
I recently found this and thought worth sharing:
import os
path = "C:\\temp\myFolder\example\\"
newPath = path.replace(os.sep, '/')
print(newPath) # -> C:/temp/myFolder/example/
Your specific problem is the order and escaping of your replace arguments, should be
s.replace('\\', '/')
Then there's:
posixpath.join(*s.split('\\'))
Which on a *nix platform is equivalent to:
os.path.join(*s.split('\\'))
But don't rely on that on Windows because it will prefer the platform-specific separator. Also:
Note that on Windows, since there is a current directory for each
drive, os.path.join("c:", "foo") represents a path relative to the
current directory on drive C: (c:foo), not c:\foo.
Try
path = '/'.join(path.split('\\'))
Path names are formatted differently in Windows. the solution is simple, suppose you have a path string like this:
data_file = "/Users/username/Downloads/PMLSdata/series.csv"
simply you have to change it to this: (adding r front of the path)
data_file = r"/Users/username/Downloads/PMLSdata/series.csv"
The modifier r before the string tells Python that this is a raw string. In raw strings, the backslash is interpreted literally, not as an escape character.
Sorry for being late to the party, but I wonder no one has suggested the pathlib-library.
pathlib is a module for "Object-oriented filesystem paths"
To convert from windows-style (backslash)-paths to forward-slashes (as typically for Posix-Paths) you can do so in a very verbose (AND platform-independant) fashion with pathlib:
import pathlib
pathlib.PureWindowsPath(r"C:\folderA\folderB").as_posix()
>>> 'C:/folderA/folderB'
Be aware that the example uses the string-literal "r" (to avoid having "\" as escape-char)
In other cases the path should be quoted properly (with double backslashes) "C:\\folderA\\folderB"
To define the path's variable you have to add r initially, then add the replace statement .replace('\\', '/') at the end.
for example:
In>> path2 = r'C:\Users\User\Documents\Project\Em2Lph\'.replace('\\', '/')
In>> path2
Out>> 'C:/Users/User/Documents/Project/Em2Lph/'
This solution requires no additional libraries
How about :
import ntpath
import posixpath
.
.
.
dir = posixpath.join(*ntpath.split(s))
.
.
This can work also:
def slash_changer(directory):
if "\\" in directory:
return directory.replace(os.sep, '/')
else:
return directory
print(slash_changer(os.getcwd()))
this is the perfect solution put the letter 'r' before the string that you want to convert to avoid all special characters likes '\t' and '\f'...
like the example below:
str= r"\test\hhd"
print("windows path:",str.replace("\\","\\\\"))
print("Linux path:",str.replace("\\","/"))
result:
windows path: \\test\\hhd
Linux path: /test/hhd

How to convert back-slashes to forward-slashes?

I am working in python and I need to convert this:
C:\folderA\folderB to C:/folderA/folderB
I have three approaches:
dir = s.replace('\\','/')
dir = os.path.normpath(s)
dir = os.path.normcase(s)
In each scenario the output has been
C:folderAfolderB
I'm not sure what I am doing wrong, any suggestions?
I recently found this and thought worth sharing:
import os
path = "C:\\temp\myFolder\example\\"
newPath = path.replace(os.sep, '/')
print(newPath) # -> C:/temp/myFolder/example/
Your specific problem is the order and escaping of your replace arguments, should be
s.replace('\\', '/')
Then there's:
posixpath.join(*s.split('\\'))
Which on a *nix platform is equivalent to:
os.path.join(*s.split('\\'))
But don't rely on that on Windows because it will prefer the platform-specific separator. Also:
Note that on Windows, since there is a current directory for each
drive, os.path.join("c:", "foo") represents a path relative to the
current directory on drive C: (c:foo), not c:\foo.
Try
path = '/'.join(path.split('\\'))
Path names are formatted differently in Windows. the solution is simple, suppose you have a path string like this:
data_file = "/Users/username/Downloads/PMLSdata/series.csv"
simply you have to change it to this: (adding r front of the path)
data_file = r"/Users/username/Downloads/PMLSdata/series.csv"
The modifier r before the string tells Python that this is a raw string. In raw strings, the backslash is interpreted literally, not as an escape character.
Sorry for being late to the party, but I wonder no one has suggested the pathlib-library.
pathlib is a module for "Object-oriented filesystem paths"
To convert from windows-style (backslash)-paths to forward-slashes (as typically for Posix-Paths) you can do so in a very verbose (AND platform-independant) fashion with pathlib:
import pathlib
pathlib.PureWindowsPath(r"C:\folderA\folderB").as_posix()
>>> 'C:/folderA/folderB'
Be aware that the example uses the string-literal "r" (to avoid having "\" as escape-char)
In other cases the path should be quoted properly (with double backslashes) "C:\\folderA\\folderB"
To define the path's variable you have to add r initially, then add the replace statement .replace('\\', '/') at the end.
for example:
In>> path2 = r'C:\Users\User\Documents\Project\Em2Lph\'.replace('\\', '/')
In>> path2
Out>> 'C:/Users/User/Documents/Project/Em2Lph/'
This solution requires no additional libraries
How about :
import ntpath
import posixpath
.
.
.
dir = posixpath.join(*ntpath.split(s))
.
.
This can work also:
def slash_changer(directory):
if "\\" in directory:
return directory.replace(os.sep, '/')
else:
return directory
print(slash_changer(os.getcwd()))
this is the perfect solution put the letter 'r' before the string that you want to convert to avoid all special characters likes '\t' and '\f'...
like the example below:
str= r"\test\hhd"
print("windows path:",str.replace("\\","\\\\"))
print("Linux path:",str.replace("\\","/"))
result:
windows path: \\test\\hhd
Linux path: /test/hhd

Python: subprocess.Popen variable behavior

I want to read all files in a directory and pass them via command line to another program.
The following is a part of my code (for one file here) which does not seem to work, and I don't really understand why it would not work.
My code (with a bit of debug print):
# -*- coding: iso-8859-15 -*-
# Python 3
avidemux_dir = "C:\\Program Files (x86)\\Avi Demux\\avidemux.exe"
start_dir = "F:\\aaa" # without ending backslash!
extension = ".mpg"
import os
import subprocess
for dirpath, dirnames, filenames in os.walk(start_dir):
if filenames:
first_file = os.path.join(dirpath, filenames[0])
test2 = "--load " + first_file
print(dirpath) #results in: F:\aaa\av01
print(first_file) #results in: F:\aaa\av01\av01.mpg
print(test2) #results in: --load F:\aaa\av01\av01.mpg
p1 = subprocess.Popen([avidemux_dir, "--load", first_file])
p2 = subprocess.Popen([avidemux_dir, test2])
For this example, avidemux will work (load the correct file) only for p1. p2 does not work.
Why is that?
The commandline example that works in .bat:
avidemux.exe --load F:\aaa\av01\av01.mpg
I really would like to have it all in one string like in p2 because I join a larger list of files together to one big string with the correct variables for avidemux.
shlex is one approach, but from the files paths it's obvious you're running on Windows, and shlex assumes conventions used in Unix-ish shells. They can get you in trouble on Windows.
As the docs say, the underlying Windows API call takes a single string as an argument, so on Windows you're generally much better off passing a single string to Popen().
Oops! I see you've already discovered that. But at least now you know why ;-)
use
import shlex
p2 = subprocess.Popen([avidemux_dir] + shlex.split(test2))
see the docs about command args of Popen.
Ah, you're passing a string of two arguments there. You need to split it, if necessary using shlex.split:
p2 = subprocess.Popen([avidemux_dir, *shlex.split(test2)])
Or just pass a string:
p2 = subprocess.Popen(avidemux_dir + ' ' + test2, shell=True)
Just stumbled across the solution: Not using a list, when doing something like that.
Solution:
test2 = avidemux_dir + " --load " + first_file
and
p2 = subprocess.Popen(test2) # no more list but the pure string.

Python long filename support broken in Windows

I write Python script to copy files; unfortunately it keeps failing because filename is too long(>256). Is there anyway to deal with that problem?
I'm using Python 2.5.4 and Windows XP.
Cheers,
Use paths beginning with the string \\?\.
In order to use the \\?\ prefix (as already proposed), you also need to make sure you use Unicode strings as filenames, not regular (byte) strings.
For anyone else looking for solution here:
You need to add prefix \\?\ as already stated, and make sure string is unicode;
If you are using shutil, especially something like shutil.rmtree with onerror method, you'll need to modify it too to add prefix as it gets stripped somewhere on the way.
You'll have to write something like:
def remove_dir(directory):
long_directory = '\\\\?\\' + directory
shutil.rmtree(long_directory, onerror=remove_readonly)
def remove_readonly(func, path, excinfo):
long_path = path
if os.sep == '\\' and '\\\\?\\' not in long_path:
long_path = '\\\\?\\' + long_path
os.chmod(long_path, stat.S_IWRITE)
func(long_path)
This is an example for Python 3.x so all strings are unicode.
This answer by uDev suggests to add
# Fix long path access:
import ntpath
ntpath.realpath = ntpath.abspath
It seems to work for me.
Another thing that works for me is to change directory into the place to which I want to copy:
import os
import shutil
def copyfile_long_path(src, dst):
src_abs = os.path.abspath(src)
dst_abs = os.path.abspath(dst)
cwd = os.getcwd()
os.chdir(os.path.dirname(dst))
shutil.copyfile(src_abs, os.path.filename(dst))
os.chdir(cwd)
if not os.path.isfile(dst_abs):
raise Exception("copying file failed")

Using Python to call Mencoder with some arguments

I'll start by saying that I am very, very new to Python.
I used to have a Windows/Dos batch file in order to launch Mencoder with the right set of parameters, without having to type them each time.
Things got messy when I tried to improve my script, and I decided that it would be a good opportunity to try coding something in python.
I've come up with that :
#!/usr/bin/python
import sys, os
#Path to mencoder
mencoder = "C:\Program Files\MPlayer-1.0rc2\mencoder.exe"
infile = "holidays.avi"
outfile = "holidays (part1).avi"
startTime = "00:48:00"
length = "00:00:15"
commande = "%s %s -ovc copy -oac copy -ss %s -endpos %s -o %s"
os.system(commande % (mencoder, infile, startTime, length, outfile))
#Pause
raw_input()
But that doesn't work, windows complains that "C:\Program" is not recognized command.
I've trying putting some "\"" here and there, but that didn't help.
Python have two types of quotes, " and ' and they are completely equal. So easiest way to get quotes in a string is to say '"C:\Program Files\MPlayer-1.0rc2\mencoder.exe"'.
Using the raw prefix (ie r'"C:\Program Files\MPlayer-1.0rc2\mencoder.exe"') is a good idea, but that is not the error here, as none of the backslashes are followed by a letter that is an escape code. So your original string would not change at all by having an r in front of it.
use two quotes instead of one if you are doing on windows.
"\\"
I'm new to Python but I know when ever I see that problem, to fix it, the file (executable or argument) must be in quotes. Just add \" before and after any file that contains a space in it to differentiate between the command-line arguments. So, that applies to your outfile variable as well. The code should look like this...
#!/usr/bin/python
import sys, os
#Path to mencoder
mencoder = "\"C:\Program Files\MPlayer-1.0rc2\mencoder.exe\""
infile = "holidays.avi"
outfile = "\"holidays (part1).avi\""
startTime = "00:48:00"
length = "00:00:15"
commande = "%s %s -ovc copy -oac copy -ss %s -endpos %s -o %s"
os.system(commande % (mencoder, infile, startTime, length, outfile))
#Pause
raw_input()
You can even put the mencoder.exe into a directory which doesn't have a space char inside it's name (opposed to Program Files).

Categories

Resources