I have this code :
> >>> import os
> >>> os.chdir('/u01/APPLTOP/instance/domains/*.oracleoutsourcing.com/ICDomain/servers/IncentiveCompensationServer_1/logs')
> Traceback (most recent call last): File "<stdin>", line 1, in ?
> OSError: [Errno 2] No such file or directory:
> '/u01/APPLTOP/instance/domains/*.oracleoutsourcing.com/ICDomain/servers/IncentiveCompensationServer_1/logs'
> >>>
Can you please let me know how can I read asterisk (*) as Linux system command in python.
To simulate shell path expansion of '*' (as well as other glob special characters), you can use the glob module:
import glob
glob_pattern = '/u01/APPLTOP/instance/domains/*.oracleoutsourcing.com/ICDomain/servers/IncentiveCompensationServer_1/logs'
dir_paths = glob.glob(glob_pattern)
Now, assuming the above results with a single match (otherwise, it makes no sense "chdir"ing ot it), you can do:
dir_path, = dir_paths
os.chdir(dir_path)
The assingment above fails if you get no matches, or multiple matches.
Firstly, this is not a "command", let alone a "Linux system command". Rather the shell (basically a tool for starting other programs) will take your commandline, replace variables like $FOO and wildcards like * according to its rules, then build a vector of arguments which are then passed to the invoked program.
Now, as already mentioned in the comments, the asterisk replacement is called globbing. Using that as a term in a websearch, you should easily find suitable code online. If you have problems implementing one of the methods you find there, don't hesitate asking here.
Related
This question already has answers here:
What is different between makedirs and mkdir of os?
(3 answers)
Closed 7 months ago.
This seems to be very basic question but still I am confused. I have a windows path containing backslash, which to escape its special meaning I have used \\.
While I use print function get the path, gives me the actual return:
>>> print("C:\\Users\\2.0Dev\\8\\F000B101\\POD280-51\\Resources")
C:\Users\2.0Dev\8\F000B101\POD280-51\Resources
however, when the same is passed as an argument to two different functions in python, the behavior is different :
>>> rsrc_dir="C:\\Users\\2.0Dev\\8\\F000B101\\POD280-51\\Resources"
>>> os.path.isdir(rsrc_dir)
>>> False
>>> os.mkdir('C:\\Users\\2.0Dev\\8\\F000B101\\POD280-51\\Resources')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
WindowsError: [Error 3] The system cannot find the path specified:'C:\\Users\\2.0Dev\\8\\F000B101\\POD280-51\\Resources'
Can someone please explain how the two functions interpret the same parameter. Also, how to return the formatted string same as the print function.
Much Thanks.
os.mkdir does not create intermediate catalogs, so this:
os.mkdir('C:\\Users\\2.0Dev\\8\\F000B101\\POD280-51\\Resources')
would fail if not
os.path.exists('C:\\Users\\2.0Dev\\8\\F000B101\\POD280-51')
use os.makedirs if you want recursive directory creation. Note that you might use os.path.join which will use separator appriopiate to system at which it runs, in your case usage would be:
rsrc_dir=os.path.join("C:\\","Users","2.0Dev","8","F000B101","POD280-51","Resources")
I am writing a program where you need to input a title for a file. If you want to delete the file, the command ss "rm name_of_file".
Here Is My Code:
import os
title = raw_input("What Will Your Title Be? ")
os.system("rm", title)
As you can probably imagine, that is only a very small part of the program I am writing.
The Error I Am Getting Is:
File "./texts.py", line 1446, in <module>
os.system("rm", title)
TypeError: system() takes exactly 1 argument (2 given)
I am probably just wording this wrong, and some feedback would be helpful :)
The comma separates it into two arguments, so you are getting that error because that function only takes one argument. Change it so you are adding to the same string thus submitting just one argument to make it work:
os.system("rm "+title)
This is going to be exceedingly hard to implement safely. Consider the case when someone types -rf / as the filename to delete. I'd strongly suggest using the os.unlink function instead:
>>> import os
>>> os.unlink('-rf /')
...
OSError: [Errno 2] No such file or directory: '-rf /'
This is a dangerous operation to attempt on your own. Let the standard library do the heavy lifting for you.
Why don't you just do
if os.path.isfile(title):
os.remove(title)
I am working on a calculator program as a part of a much larger project and when I finally thought I had it finished I tested the defined "quit" command. However, it failed and after some research, I came here. What I need to know is how to make the (path) argument have a set, pre-defined path, but also have a variable for the actual file name. eg: /HDD/APPS/(insert variable here).
This is the error and the line that the error occurred on:
File "../../C.py", line 19
if ( not os.path.isfile('/HDD/APPS/'exe)):
^
SyntaxError: invalid syntax
Concatenate two strings:
>>> exe = 'exefile'
>>> '/HDD/APPS/' + exe
'/HDD/APPS/exefile'
More preferably, use os.path.join:
>>> import os
>>> os.path.join('/HDD/APPS/', exe)
'/HDD/APPS/exefile'
I am trying to change the current working directory in python using os.chdir. I have the following code:
import os
os.chdir("C:\Users\Josh\Desktop\20130216")
However, when I run it, it seems to change the directory, as it comes out with the following error message:
Traceback (most recent call last):
File "C:\Users\Josh\Desktop\LapseBot 1.0\LapseBot.py", line 3, in <module>
os.chdir("C:\Users\Josh\Desktop\20130216")
WindowsError: [Error 2] The system cannot find the file specified
'C:\\Users\\Josh\\Desktop\x8130216'
Can anyone help me?
Python is interpreting the \2013 part of the path as the escape sequence \201, which maps to the character \x81, which is ü (and of course, C:\Users\Josh\Desktopü30216 doesn't exist).
Use a raw string, to make sure that Python doesn't try to interpret anything following a \ as an escape sequence.
os.chdir(r"C:\Users\Josh\Desktop\20130216")
You could also use os.path.join (documentation).
Example:
os.chdir(os.path.join('C:\Users\Josh\Desktop', '20130216'))
This is more elegant + it's compatible with different operating systems.
This should work -
os.chdir("C:\Users\Josh\Desktop\\20130216")
There are two to use os.chdir():
If you are using raw string than use single backslash \:
os.chdir(r"C:\Users\Josh\Desktop\20130216")
or
If you are not using raw string than use double backslash \\
os.chdir("C:\Users\Josh\Desktop\20130216")
I have faced the same problem but you have to try:
os.chdir(c:\\user\\Josh\\Desktop)
Use \\ so maybe you should get your solution.
I'm writing a small script, that should be able to handle multiple files. So I've added that files can be passed comma seperated, and do a arg.split(',') and then handle each one.
Now I've wanted to add asterisk as input possibility like
python myPythonScript.py -i folder/*
If I print the the argument to option -i right when I access it the first time I get
folder/firstFileInFolder.txt
But if I call my script with
python myPythonScript.py -i someFolder/someFile,folder/*
it works just fine. Does anyone have an idea, why python might behave that way?
Try to run this script
import sys
for arg in sys.argv:
print arg
python script.py *
your shell expands the asterisk before python sees it.
As mentioned in the comments, your shell is expanding the asterisk for the non-comma separated case. If you know that the user may specify an asterisk as part of a file name as in your second example, you can have Python do the path expansion by using the glob module.
from glob import glob
glob('*')
code which would allow either the shell or Python to do asterisk expansion may look something like this:
import glob
file_list = []
for pattern in sys.argv[1:]:
file_list.extend(glob.glob(pattern))
In your case, using a comma as a separator would then prevent you from using a comma as part of a filename.