sys.argv arguments with spaces - python

I'm trying to input folder names as sys.argv arguments, but am having problem with folder names that have spaces, which become multiple variables.
For example, from the command line below, "Folder Name" becomes two variables.
Program.py D:\Users\Erick\Desktop\Folder Name
Any solutions?

Space is the delimiter for command line arguments. You'll be better off not using spaces in your directory and file names if possible. For entering an argument which has space in it you'll have to enclose it in quotes "folder with space".
Program.py "D:\Users\Erick\Desktop\Folder Name"

Assuming input is always going to be a single file/folder path:
path = " ".join(sys.argv[1:])

To extend the simplicity of Arshiyan's answer for a case involving multiple paths, you could join the paths with a delimiter such as a hash, and then split the resulting string when it gets to python...
paths = " ".join(sys.argv[1:]).split("#")

Related

Handling quotes and spaces in filenames

I want to create a Python (3) script that passes files to a Linux shell program. Straightforward enough to do, but I'm not sure how to pass filenames that could contain single- or double-quotes and spaces to the shell. I would presumably need to delimit filenames in case they contain spaces.
I might consider a command string something like f"wc -c '{filename}'", but that would break down if I encounter a filename containing a single quote. Likewise if I delimit with double-quotes and encounter a file containing those.
As something like Bob's "special" file would be a valid ext4 filename, how do I cope with all the possibilities?
As Tim Roberts mentioned in comments, you can use subprocess module to bypass this problem. Here is a short example (assuming you have a list of filenames) for passing a list of filenames to wc -c:
from subprocess import run
# assuming you have got a list of filenames
filenames = ['test.py', "Bob's special file", 'test space.py']
for filename in filenames:
run(['wc', '-c', filename])
By the way, if you want to use Python to get all filenames under one specific directory,
you might consider os.listdir.

Alternative way to change from a string literal to a raw string literal when reading in a file path

I am writing a function and my input parameter is the file path: C:\Users\HP\Desktop\IBM\New folder
def read_folder(pth):
for fle in Path(pth).iterdir():
file_name = Path(pth) / fle
return file_name
For me to use this function, I need to specify r'' in the file path, ie.
read_folder(r'C:\Users\HP\Desktop\IBM\New folder')
Is there a way where I can avoid specifying r'' in the file path, ie. like the below and the code would work.
read_folder('C:\Users\HP\Desktop\IBM\New folder')
The reason why I want to do this is so to make it easier for the user to just copy and paste the directory path into the function and just run the function. So it's more for ease-of-use on the user end.
Many thanks.
You can't really do that because without prepending r to your string there's no way python interpreter would know that your string contains \ intentionally and not on purpose to escape the characters.
So you've to either use r"C:\Users\HP\Desktop\IBM\New folder" or "C:\\Users\\HP\\Desktop\\IBM\New folder" as argument while calling read_folder function.
You can escape the backslashes:
read_folder('C:\\Users\\HP\\Desktop\\IBM\New folder')

Ghostcript destination name with blank space returns error [duplicate]

I have a main file which uses(from the main I do a source) a properties file with variables pointing to paths.
The properties file looks like this:
TMP_PATH=/$COMPANY/someProject/tmp
OUTPUT_PATH=/$COMPANY/someProject/output
SOME_PATH=/$COMPANY/someProject/some path
The problem is SOME_PATH, I must use a path with spaces (I can't change it).
I tried escaping the whitespace, with quotes, but no solution so far.
I edited the paths, the problem with single quotes is I'm using another variable $COMPANY in the path
Use one of these threee variants:
SOME_PATH="/mnt/someProject/some path"
SOME_PATH='/mnt/someProject/some path'
SOME_PATH=/mnt/someProject/some\ path
I see Federico you've found solution by yourself.
The problem was in two places. Assignations need proper quoting, in your case
SOME_PATH="/$COMPANY/someProject/some path"
is one of possible solutions.
But in shell those quotes are not stored in a memory,
so when you want to use this variable, you need to quote it again, for example:
NEW_VAR="$SOME_PATH"
because if not, space will be expanded to command level, like this:
NEW_VAR=/YourCompany/someProject/some path
which is not what you want.
For more info you can check out my article about it http://www.cofoh.com/white-shell
You can escape the "space" char by putting a \ right before it.
SOME_PATH=/mnt/someProject/some\ path
should work
If the file contains only parameter assignments, you can use the following loop in place of sourcing it:
# Instead of source file.txt
while IFS="=" read name value; do
declare "$name=$value"
done < file.txt
This saves you having to quote anything in the file, and is also more secure, as you don't risk executing arbitrary code from file.txt.
If the path in Ubuntu is "/home/ec2-user/Name of Directory", then do this:
1) Java's build.properties file:
build_path='/home/ec2-user/Name\\ of\\ Directory'
Where ~/ is equal to /home/ec2-user
2) Jenkinsfile:
build_path=buildprops['build_path']
echo "Build path= ${build_path}"
sh "cd ${build_path}"

How to save a dataframe as a csv file with '/' in the file name

I want to save a dataframe to a .csv file with the name '123/123', but it will split it in to two strings if I just type like df.to_csv('123/123.csv').
Anyone knows how to keep the slash in the name of the file?
You can't use a slash in the name of the file.
But you can use Unicode character that looks like slash if your file system support it http://www.fileformat.info/info/unicode/char/2215/index.htm
... "/" is used for indicating a path to a child folder, so your filename says the file 123.csv is in a folder "123"
however, that does not make it entirely impossible, just very difficult see this question:
https://superuser.com/questions/187469/how-would-i-go-about-creating-a-filename-with-invalid-characters-such-as
and that a charmap can find a character that looks like it, which is legal. In this case a division character
You can not use any of these chars in the file name ;
/:*?\"|
You can use a similar unicode character as the "Fraction slash - Unicode hexadecimal: 0x2044"
Example:
df.to_csv("123{0}123".format(u'\u2044'.encode('utf-8')))
It gives you the filename that you asked.

A python function with a complicated argument

I have a function in a python code whose argument is as follows:
save_geometry(r"""C:\Users\User0\Documents\test.txt """)
I want to modify the argument and be able to save to a different path with a different filename:
filename = "geometries.txt "
filepath = "D:/AllData/"
filefullpath = filepath + filename
Could someone help me how I should pass filefullpath to save_geometry? If there were no r in the argument of save_geometry, it would be easy. But I don't know how to deal with this r.
The r"" construct just tells Python that whatever's in the string should be interpreted as raw data.
"qw\n" == 'qw\n'
r"qw\n" == 'qw\\n'.
It's used because the "\" path separator is also used for newlines and such. You can skip it when putting in the argument; save_geometry(filefullpath) should do what you expect.
Note that the canonical way of putting together paths is os.path.join
path = os.path.join("D:\\", "AllData", "geometries.txt")
User3757614's answer addresses your concern of the raw string notation, but succinctly all the r"" notation does is tell Python that the following string should not treat \ as an escape character, but as a literal backslash. This is important since "C:\new folder" is actually
C:
ew folder
Since \n is a newline.
You cans use the os module to split your string into a folder path and file name.
e.g.
import os
pathname = os.path.dirname('C:\Users\User0\Documents\test.txt') #C:\Users\User0\Documents
filename = os.path.basename('C:\Users\User0\Documents\test.txt') #test.txt
Though you'll need to modify your path string because your \s will be interpreted and newline bytes

Categories

Resources