0

This is just maddening--I have a file with an & sign in the middle of it. When my python script went to open it, the & sign acted as an end of command character or something....

Can anyone tell me how to get around this? Or better yet, I would love to know where to look for a list of all of these special characters for the terminal.

Thanks in advance

--A mac noob

Mizmor
  • 1,391
  • 6
  • 21
  • 43

4 Answers4

2

The Bash command & means execute in background, it is interpreting & as a command and not an argument to your command, either remove it from the filename, which is good anyway, or escape it like \&

OpenCoderX
  • 6,180
  • 7
  • 34
  • 61
2

You can also surround the whole name with single quotes. Single quotes defend a filename from almost all kinds of interpretation - ampersands, angle brackets, whitespace, etc. They are often easier to use than backslashes, because you don't need to specifically apply them to every troublesome character, you just quote the whole filename.

Now, why was this a problem in a Python script? What were you doing that the shell's handling of filenames was relevant? That doesn't sound at all right.

Tom Anderson
  • 46,189
  • 17
  • 92
  • 133
  • Opening a file to display to the user. In order to open it, I needed the file name and to call open from the terminal. The file name contains the & character--Hence the need to interpret it differently. – Mizmor Jun 27 '12 at 22:19
  • Aha. The right way to run external programs is with the functions in the [subprocess](http://docs.python.org/library/subprocess.html) module. Arguments passed though those functions are not subject to interpretation by the shell, so there is no need to escape them. They avoid this problem altogether. – Tom Anderson Jun 27 '12 at 22:33
0

You can use the escape character, \. So all you have to do is put backslashes in this:
open file&with&an&ampersand.txt
To make it this:
open file\&with\&an\&ampersand.txt

andrew
  • 448
  • 7
  • 13
0

in addition to @Tom answer i think you have to escape single quote in file names because files can have single quote in there name and you can do this by replacing single quote with '"'"' please check this answer: https://stackoverflow.com/a/1250279/427622

Community
  • 1
  • 1
Fareed Alnamrouti
  • 30,771
  • 4
  • 85
  • 76