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")
Related
This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 6 months ago.
I am learning about file objects in python but whenever i try to open file it shows the following error.
I have already checked that file is in same directory and it exists
this error occurs only if i name my file as test if i use any other name then it works fine
here's my CODE
f = open('C:\\Users\Tanishq\Desktop\python tutorials\test.txt', 'r')
here's the ERROR
Traceback (most recent call last):
File "C:/Users/Tanishq/Desktop/question.py", line 1, in <module>
f = open('C:\\Users\Tanishq\Desktop\python tutorials\test.txt', 'r')
OSError: [Errno 22] Invalid argument: 'C:\\Users\\Tanishq\\Desktop\\python
tutorials\test.txt'
Your issue is with backslashing characters like \T :
Try:
f = open(r'C:\\Users\Tanishq\Desktop\python tutorials\test.txt', 'r')
Python uses \ to denote special characters. Therefore, the string you provided does not actually truly represent the correct filepath, since Python will interpret \Tanishq\ differently than the raw string itself. This is we we place the r in front of it. This lets Python know that we do indeed want to use the raw string and to treat \ as a normal character.
This question already has answers here:
str.translate gives TypeError - Translate takes one argument (2 given), worked in Python 2
(4 answers)
Translate function in Python 3 [duplicate]
(4 answers)
Closed 5 years ago.
This is an assignment that needs to change the name of the file within a certain folder, however, it doesn't change the name after all. Can anyone help?
import os
def rename_files():
file_list = os.listdir(r"C:\Users\Downloads\prank")
saved_path = os.getcwd()
print("Current Working Directory is " +saved_path)
os.chdir(r"C:\Users\Downloads\prank")
for file_name in file_list:
os.rename(file_name, file_name.translate(None, "0123456789"))
os.chdir(saved_path)
rename_files()
result:
Traceback (most recent call last):
File "C:\Users\Downloads\prank\rename_files.py", line 10, in <module>
rename_files()
File "C:\Users\Downloads\prank\rename_files.py", line 8, in rename_files
os.rename(file_name, file_name.translate(None, '0123456789'))
TypeError: translate() takes exactly one argument (2 given)
This code works in Python 2, but does not work in Python 3. How can it be made to work in Python 3.6, I only need to delete characters.
You are confusing the Python 2 str.translate() method with the Python 3 version (which is really the same as unicode.tranlate() in Python 2).
You can use the str.maketrans() static method to create a translation map; pass your string of digits to be removed in as the third argument to that function:
file_name.translate(str.maketrans('', '', '0123456789'))
Better still, store the result of str.maketrans() outside of the loop, and re-use it:
no_digits = str.maketrans('', '', '0123456789')
for file_name in file_list:
os.rename(file_name, file_name.translate(no_digits))
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.
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.
This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 6 months ago.
So I have a script that needs to print to a file in a different directory. I give that absolute path and python doesn't like it.
Here's where the file is located:
C:\Users\Owner\Documents\Senior_design\QT_Library\build-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\numbers.txt
(I know, long path, but QT plotter makes the file names really long)
I typed:
textfile = open('C:\Users\Owner\Documents\Senior_design\QT_Library\build-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\numbers.txt', 'w')
And I get this error:
IOError: [Errno 22] invalid mode ('w') or filename:
I've read that I can use relative paths, but I am unsure how to give it a relative path with so many directories to go through.
Thanks!
The problem is that python is interpreting the backslashes in your path as escape sequences:
>>> 'C:\Users\Owner\Documents\Senior_design\QT_Library\build-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\numbers.txt'
'C:\\Users\\Owner\\Documents\\Senior_design\\QT_Library\x08uild-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\numbers.txt'
Notice that both \b and \n get translated to something else. Use a "raw" string instead:
>>> r'C:\Users\Owner\Documents\Senior_design\QT_Library\build-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\numbers.txt'
'C:\\Users\\Owner\\Documents\\Senior_design\\QT_Library\\build-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\\numbers.txt'
I believe this answer here may be of help.
Essentially, your backslashes are causing issues.