How to Concatenate Two Strings to Build a Complete Path

Concatenate path and filename

Backslash character (\) has to be escaped in string literals.

  • This is wrong: '\'
  • This is correct: '\\' - this is a string containing one backslash

Therefore, this is wrong:

'C:\Program Files (x86)\LibreOffice 5\program\soffice.exe'

There is a trick!

String literals prefixed by r are meant for easier writing of regular expressions. One of their features is that backslash characters do not have to be escaped. So, this would be OK:

r'C:\Program Files (x86)\LibreOffice 5\program\soffice.exe'

However, that wont work for a string ending in backslash:

  • r'\' - this is a syntax error

So, this is also wrong:

r'C:\Users\A\Desktop\Repo\'

So, I would do the following:

import os
import subprocess


soffice = 'C:\\Program Files (x86)\\LibreOffice 5\\program\\soffice.exe'
outdir = 'C:\\Users\\A\\Desktop\\Repo\\'
full_path = os.path.join(outdir, filename)

subprocess.call([soffice,
'--headless',
'--convert-to', 'pdf',
'--outdir', outdir,
full_path])

How to join paths in shell script

The current working directory can be obtained in bash with the command pwd.

Usually, the variable $PWD contains the directory. So something like that should do:

full_path="${PWD}/foo.txt"

and by calling the pwd command:

full_path="$(pwd)/foo.txt"

Combine two strings to a single string representing a path

FilenameUtils.normalize() from Apache Commons IO does what you want.

example:

FilenameUtils.normalize("foo/" + "/bar");

returns the string "foo/bar"

In a batch file, combining two strings to create a combined path string

Environment variables you set in a subprocess cannot be passed to the calling process. A process' environment is a copy of its parent's but not vice versa. However, you can simply output the result in PowerShell and read that output from the batch file:

for /f "delims=" %%x in ('powershell -file foo.ps1') do set joinedpath=%%x

Still, since PowerShell needs about a second to start this may not be optimal. You can certainly do it in a batch file with the following little subroutine:

:joinpath
set Path1=%~1
set Path2=%~2
if {%Path1:~-1,1%}=={\} (set Result=%Path1%%Path2%) else (set Result=%Path1%\%Path2%)
goto :eof

This simply looks at the very last character of the first string and if it's not a backslash it will add one between the two – pretty simple, actually.

Sample output:

JoinPath "C:\trunk" "ProjectName\Project.txt"
-- C:\trunk\ProjectName\Project.txt
JoinPath "C:\trunk\" "ProjectName\Project.txt"
-- C:\trunk\ProjectName\Project.txt

The code and sample batch file can be found in my SVN but are reproduced here since they're quite brief anyway:

@echo off
echo JoinPath "C:\trunk" "ProjectName\Project.txt"
call :joinpath "C:\trunk" "ProjectName\Project.txt"
echo -- %Result%

echo JoinPath "C:\trunk\" "ProjectName\Project.txt"
call :joinpath "C:\trunk\" "ProjectName\Project.txt"
echo -- %Result%

goto :eof

:joinpath
set Path1=%~1
set Path2=%~2
if {%Path1:~-1,1%}=={\} (set Result=%Path1%%Path2%) else (set Result=%Path1%\%Path2%)
goto :eof

connecting multiple strings to path in python with slashes

The solution here depends on the context: How much power do you want to give your users? How much do you trust them to input something sensible? Is the result you want to get a relative path or an absolute path?

  • Option 1: Power to the users

    Let the users do whatever they want and make it their own responsibility to get it right:

    result = os.path.join(mr, cn, lp, vin)
    # result: '/data/dir/var'

    This gives the users the maximum degree of control.

  • Option 2: Force everything to be relative

    If you want to force every individual segment to be a relative path, there's no way around stripping any leading path separators.

    seps = r'\/'  # backslash for windows, slash for all platforms
    fragments = [part.strip(seps) for part in [mr, cn, lp, vin]]
    result = os.path.join(*fragments)
    # result: 'mapr/12.12.12/data/dir/var'

    If you need the result to be an absolute path, join it with your root directory:

    seps = r'\/'
    root = '/var/log'
    fragments = [part.strip(seps) for part in [mr, cn, lp, vin]]
    result = os.path.join(root, *fragments)
    # result: '/var/log/mapr/12.12.12/data/dir/var'

Function to concatenate paths?

Yes, file.path()

R> file.path("usr", "local", "lib")
[1] "usr/local/lib"
R>

There is also the equally useful system.path() for files in a package:

R> system.file("extdata", "date_time_zonespec.csv", package="RcppBDT")
[1] "/usr/local/lib/R/site-library/RcppBDT/extdata/date_time_zonespec.csv"
R>

which will get the file extdata/date_time_zonespec.csv irrespective of

  1. where the package is installed, and
  2. the OS

which is very handy. Lastly, there is also

R> .Platform$file.sep
[1] "/"
R>

if you insist on doing it manually.

Platform independent path concatenation using / , \ ?

You want to use os.path.join() for this.

The strength of using this rather than string concatenation etc is that it is aware of the various OS specific issues, such as path separators. Examples:

import os

Under Windows 7:

base_dir = r'c:\bla\bing'
filename = r'data.txt'

os.path.join(base_dir, filename)
'c:\\bla\\bing\\data.txt'

Under Linux:

base_dir = '/bla/bing'
filename = 'data.txt'

os.path.join(base_dir, filename)
'/bla/bing/data.txt'

The os module contains many useful methods for directory, path manipulation and finding out OS specific information, such as the separator used in paths via os.sep

How to concatenate path and varying file names - C++

To concatenate strings. Use std::string instead of char*.
like:

#include <string>
#include <iostream>
#include <fstream>
int main() {
std::string path = "path";
std::string file = "file.txt";
std::string myfile = path + "/" + "file.txt";
std::string fname = "test.txt";
std::ofstream f(fname);
f << myfile;
}

this will write "path/file.txt" in the file named test.txt.



Related Topics



Leave a reply



Submit