Python OSError while attempting os.mkdir [duplicate] - python

This question already has answers here:
How can I put an actual backslash in a string literal (not use it for an escape sequence)?
(4 answers)
Closed 7 months ago.
import os
directory=input("Directory: ")
if not os.path.exists(directory):
os.mkdir(directory)
os.mkdir(str(directory)+'\steamCMD')
os.mkdir(str(directory)+'\temporary')
A snippet from my code. Returns OSError on the last line shown here. Why? Does exactly same thing as 5th line yet 5th line works like a charm.
Error:
os.mkdir(str(directory)+'\temporary')
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'c:\\testing\temporary'
Similar: Python - os.rename() - OSError: [WinError 123]
os.mkdir(path) returns OSError when directory does not exist
However he had different mistake to me. Anyone tell me why this is happen?

Try:
os.mkdir(str(directory) + '\\temporary')
Or
os.mkdir(str(directory) + r'\temporary')
About the two \\ or r'\temporary', here is the documentation and here is a good question.
Also, os.path.join() is a good choice because which uses \\ on Windows but / on *nix. For example:
os.mkdir(os.path.join(directory), 'temporary')
This gives directory\temporary on Windows and directory/temporary on *nix. It is a more clear and simple way.

Related

Python not interpreting wildcard * properly?

For some reason, python doesn't seem to recognize my wildcard command using *.r.
A MWE:
filepath = "C:/outputs"
os.remove(f'{filepath}/*.r')
Python returns the following error:
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:/outputs/*.r'
I know there are alternatives to using the "*.r" method, such as using a "for file in os.listdir(...): if file.endswith('.r'): os.remove(file)" etc. But the "os.remove('./*.r')" method works in my other python files, so this is just driving me insane. What might be going wrong?

python finding file error with wrong file referenced [duplicate]

This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 2 years ago.
I have isolated a problematic part of my code and run it as 3 lines (see below), yet I still get this weird error where python tells me I used invalid argument, which looks different than the argument passed in. It apparently at random replaces one of my backslashes by double back slash (which shouldn't matter) and alters the name of the file i want opened.
Code:
fl = open("D:\test\sysi\temporary\fe_in.txt","rt")
flstr = fl.read()
ff = flstr.split("---")[1]
Error:
OSError: [Errno 22] Invalid argument: 'D:\test\\sysi\temporary\x0ce_in.txt'
Anybody has encountered this? Any ideas what could be causing this or what could I try? (I have already deleted and re-created the file in question thinking it could be corrupted, didn't change anything)
I tested it and I needed to use double slash "\\" to use this without your error:
fl = open("D:\\test\\sysi\\temporary\\fe_in.txt","rt")
flstr = fl.read()
ff = flstr.split("---")[1]
I believe it is because a single slash will be used as an escape character.
We do not know if your file is corrupted as you suspected in you question since the argument to "open" already was invalid. Your textfile was never opened before the error.
Now I only get, "[Errno 2] No such file or directory: 'D:\test\sysi\temporary\fe_in.txt'" because I did not place a file like yours in my file system, but if you have it the program should succeed.
try:
open(r"D:\test\sysi/temporary\fe_in.txt","r")
or
open(r"D:/test/sysi/temporary/fe_in.txt","r")
or
path = r"D:\test\sysi\temporary\fe_in.txt"
surely someone will work

Python subprocess File not found [duplicate]

This question already has answers here:
subprocess.Popen() error (No such file or directory) when calling command with arguments as a string
(2 answers)
Closed 2 years ago.
I am trying to find the file type using file with subprocess
cwdir = os.getcwd()
Fileinput=cwdir+"/"+'testfile.zip'
print "Current Directory %s"% cwdir
Fileformat=subprocess.Popen('file' + Fileinput)
I get OSError: [Errno 2] No such file or directory. I verified and the file does exist in the path.
Thanks for any help with this.
Add space between 'file' and fileinput
Fileformat = subprocess.Popen('file ' + Fileinput)
# ^
Otherwise, file/current/path/testfile.zip is treated as executable path instead of file.
Or use following form:
Fileformat = subprocess.Popen(['file', Fileinput])
you have to pass stdout=subprocess.PIPE to Popen and read using Fileformat.stdout.read() if you want get output of the command.
How about using subprocess.check_output?
>>> subprocess.check_output(['file', '/etc/passwd'])
'/etc/passwd: ASCII text\n'

Python error: "cannot find path specified" [duplicate]

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 22 days ago.
import os
import random
os.chdir("C:\Users\Mainuser\Desktop\Lab6")
#Am i supposed to have a os.chdir?
# I think this is what's giving the error
#how do i fix this?
def getDictionary():
result = []
f = open("pocket-dic.txt","r")
for line in f:
result = result + [ line.strip() ];
return result
def makeText(dict, words=50):
length = len(dict)
for i in range(words):
num = random.randrange(0,length)
words = dict[num]
print word,
if (i+1) % 7 == 0:
print
Python gives me an error saying it cannot find the path specified, when i clearly have a folder on my desktop with that name. It might be the os.chidr?? what am i doing wrong?
Backslash is a special character in Python strings, as it is in many other languages. There are lots of alternatives to fix this, starting with doubling the backslash:
"C:\\Users\\Mainuser\\Desktop\\Lab6"
using a raw string:
r"C:\Users\Mainuser\Desktop\Lab6"
or using os.path.join to construct your path instead:
os.path.join("c:", os.sep, "Users", "Mainuser", "Desktop", "Lab6")
os.path.join is the safest and most portable choice. As long as you have "c:" hardcoded in the path it's not really portable, but it's still the best practice and a good habit to develop.
With a tip of the hat to Python os.path.join on Windows for the correct way to produce c:\Users rather than c:Users.
Backslashes have special meaning inside Python strings. You either need to double them up or use a raw string: r"C:\Users\Mainuser\Desktop\Lab6" (note the r before the opening quote).

File not found Error in reading text in python [duplicate]

This question already has answers here:
How should I write a Windows path in a Python string literal?
(5 answers)
Closed 7 months ago.
I am trying to read a text file on my hard drive via python with the following script:
fileref = open("H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")
But it is giving the following error:
IOError Traceback (most recent call last)
<ipython-input-2-4f422ec273ce> in <module>()
----> 1 fileref = open("H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")
IOError: [Errno 2] No such file or directory: 'H:\\CloudandBigData\x0cinalproj\\BeautifulSoup\twitter.txt'
I also tried with other way:
with open('H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt', 'r') as f:
print f.read()
Ended up with the same error. The text file is present in the directory specified.
Replace
fileref = open("H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")
with
fileref = open(r"H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")
Here, I have created a raw string (r""). This will cause things like "\t" to not be interpreted as a tab character.
Another way to do it without a raw string is
fileref = open("H:\\CloudandBigData\\finalproj\\BeautifulSoup\\twitter.txt","r")
This escapes the backslashes (i.e. "\\" => \).
An even better solution is to use the os module:
import os
filepath = os.path.join('H:', 'CloudandBigData', 'finalproj', 'BeautifulSoup', 'twitter.txt')
fileref = open(filepath, 'r')
This creates your path in an os-independent way so you don't have to worry about those things.
One last note... in general, I think you should use the with construct you mentioned in your question... I didn't in the answer for brevity.
I was encountering same problem. This problem resulted due to different file path notation Python.
For example, filepath in Windows reads with backward slash like: "D:\Python\Project\file.txt"
But Python reads file path with forward slash like: "D:/Python/Project/file.txt"
I used r"filepath.txt" and "os.path.join" and "os.path.abspath" to no relief. os library also generates file path in Windows notation. Then I just resorted to IDE notation.
You don't encounter this error if "file.txt" is located in same directory, as filename is appended to working directory.
PS: I am using Python 3.6 with Spyder IDE on Windows machine.

Categories