Python creating directory gives IO error - python

I extract the directory name from the path which is BounceOM, then i have a filename which is HelloWorld.
I want to create new folder 'HelloWorld' in the BounceOM directory. I use os.path.join
filename=os.path.basename(str(htmlfile)).replace('.mat',' ')
path=os.path.dirname(os.path.abspath(str(resultfile)))
newpath=os.path.join(path,filename)
my new path prints, C:\Users\rain1_000\Desktop\python\BounceOM\HelloWorld
Then I try to create the directory
if not os.path.exists(newpath):
os.makedirs(newpath)
I want to store some files in the new directory, but it gives me IOError: [Errno 2] No such file or directory: But when I look into the directory, Helloworld directory is created,
But when I append single quotes to the filename and create the directory then it does not gives me error and result files are written to the newly created directory
report1='\''+filename+'\''
newpath=os.path.join(path,report1)
my new path prints, C:\Users\rain1_000\Desktop\python\BounceOM\'HelloWorld' and there is no problem in creating and writing the result files.
I don't understand what is the real problem

I think single quotes should not be the problem. Can you try other folder name without single quotes and check

Related

How can I open a folder with argparse

I want to open a folder containing x zipfiles.
I have this code:
parser = argparse.ArgumentParser(description='Test')
parser.add_argument("foldername", help="Foldername of log files archive to parse")
args = parser.parse_args()
with open(args.foldername) as files:
filename = args.filename
print(filename)
But I get error code:
PermissionError: [Errno 13] Permission denied: 'Test'
I would like the zipfiles in the folder to be listed in an array when I run the code.
I'm not sure why you're getting a permission error, but using open on a directory won't do what you want. The documentation for Python's open requires that its input is a string to a file, not a directory.
If you want the files in a directory given the name of the directory as a string, refer to How can I iterate over files in a given directory?
Are you sure you have permission to read those files? Test, whatever file or folder it is, doesn't seem to be readable from your script.

FileNotFoundError, when I run shutil.copy, 1 particular ".dylib" file throws FileNotFoundError error every time

I am making a python app and one of it's functions involves copying the contents of one directory to several different locations. Some of these files are copied to the same directory in which they currently reside and are renamed. It almost always works except when it hit this one particular file.
This is the code that does the copying.
shutil.copy(original_path_and_file,os.path.join(redun.path, redun.file_name))
The particular copy that causes the crash is when it's trying to copy /Users/<myusername>/Desktop/archive1/test_2_here/myproject/liboqs.dylib to /Users/<myusername>/Desktop/archive1/test_2_here/myproject/liboqs.0.dylib
This is the error that appears in my terminal:
FileNotFoundError: [Errno 2] No such file or directory: '/Users/<myusername>/Desktop/archive1/test_2_here/myproject/liboqs.dylib'
Why does this file throw the error and none of the other files that it copies throw any errors?
Update
The file is actually an "Alias" according to finder:
Perhaps you could attempt to solve it by connecting the directory path and the filename like follows:
One problem here is that you do not specify the path of the file. As you are executing the command from the parent directory, the script has no way of knowing that testfile2.txt is in a subdirectory of your input directory. To fix this, use:
shutil.copy(os.path.join(foldername, filename), copyDirAbs)
or
# Recursively walk the Search Directory, copying matching files
# to the Copy Directory
for foldername, subfolders, filenames in os.walk(searchDirAbs):
print('Searching files in %s...' % (foldername))
for filename in filenames:
if filename.endswith('.%s' % extension):
print('Copying ' + filename)
print('Copying to ' + copyDirAbs)
totalCopyPath = os.path.join(searchDirAbs, filename)
shutil.copy(totalCopyPath, copyDirAbs)
print('Done.')
The Python FileNotFoundError: [Errno 2] No such file or directory error is often raised by the os library. This error tells you that you are trying to access a file or folder that does not exist. To fix this error, check that you are referring to the right file or folder in your program.
The way I fixed this was by having the app ignore link files. I wrote this:
if not os.path.islink(original_path_and_file):
shutil.copy(original_path_and_file,os.path.join(redun.path, redun.file_name))
This is technically more of a work-around than a fix because it doesn't actually copy the file but I decided the app still works fine when not copying link files.

Python script that creates new file and returns list of files

I'm trying to create a python script called script.py with new_directory function that creates a new directory inside the current working directory, then creates a new empty file inside the new directory, and returns the list of files in that directory.
The output I get is ["script.py"] which looks correct but gives me this error:
RuntimeErrorElement(RuntimeError,Error on line 5:
directory = os.mkdir("/home/PythonPrograms")
FileExistsError: [Errno 17] File exists: '/home/PythonPrograms'
)
import os
def new_directory(directory, filename):
if os.path.isdir(directory) == False:
directory = os.mkdir("/home/PythonPrograms")
os.chdir("PythonPrograms")
with open("script.py", "w") as file:
pass
# Return the list of files in the new directory
return os.listdir("/home/PythonPrograms")
print(new_directory("PythonPrograms", "script.py"))
How do I correct and why is this wrong?
As others have said, it is hard to debug without the error. In the right cercumstances, your code will work without errors. As #Jack suggested, I suspect you're current directory is not /home. This means you've created a directory called PythonPrograms in /home directory. os.chdir("PythonPrograms") is trying to change the directory to <currentDirectory>/PythonPrograms, which doesn't exist.
I have tried to rework your code (without completely changing it), into something that should work in all cases. I think the lesson here is, work with the variables you already have (i.e. directory), rather than hardcoding it into the function.
import os
def new_directory(directory, filename):
if not os.path.isdir(directory):
# Create directory within current directory
# This is working off the relative path (from your current directory)
directory = os.mkdir(directory)
# Create file if does not exist
# this is a one-liner version of you with...pass statement
open(os.path.join(directory, filename), 'a').close()
# Return the list of files in the new directory
return os.listdir(directory)
print(new_directory("PythonPrograms", "script.py"))
I hope that helps.
I'm guessing the error you're getting is because you're not able to switch directories to PythonPrograms? This would be because your python current working directory does not contain it. If you more explicitly write out the directory you want to switch to, for example putting os.chdir("/home/PythonPrograms"), then it may work for you.
Ideally you should give us any stack traces or more info on the errors, though
I'm not sure why in your code you have with open("script.py", "w") as file: pass,
but here is mt way:
import os
os.mkdir('.\\Newfolder') # Create a new folder called Newfolder in the current directory
open('.\\Newfolder\\file.txt','w').close() # Create a new file called file.txt into Newfolder
print(os.listdir('.')) # Print out all the files in the current directory

FileNotFound Error: [Errno 2] No such file or directory b when iterating through list of files in Python on Windows?

I am getting a FileNotFound error when iterating through a list of files in Python on Windows.
The specific error I get looks like:
FileNotFoundError: File b'fileName.csv' does not exist
In my code, I first ask for input on where the file is located and generate a list using os (though I also tried glob):
directory = input('In what directory are your files located?')
fileList = [s for s in os.listdir(directory) if s.endswith('.csv')]
When I print the list, it does not contain byte b before any strings, as expected (but I still checked). My code seems to break at this step, which generates the error:
for file in fileList:
pd.read_csv(file) # breaks at this line
I have tried everything I could find on Stack Overflow to solve this problem. That includes:
Putting an r or b or rb right before the path string
Using both the relative and absolute file paths
Trying different variations of path separators (/, \, \\, etc.)
I've been dealing with Windows-related issues lately (since I normally work in Mac or Linux) so that was my first suspicion. I'd love another set of eyes to help me figure out where the snag is.
A2A.
Although the list was generated correctly because the full directory path was used, the working directory when the file was being run was .. You can verify this by running os.getcwd(). When later iterating through the list of file names, the program could not find those file names in the . directory, as it shouldn't. That list is just a list of file names; there was no directory tied to it so it used the current directory.
The easiest fix here is to change the directory the file is running through after the input. So,
directory = input('In what directory are your files located?')
os.chdir(directory) # Points os to given directory to avoid byte issue
If you need to access multiple directories, you could either do this right before you switch to each directory or save the full file path into your list instead.

Python create folder for each file in a directory

I have a directory with a set of files in it. I'm trying to create a folder for each filename inside the existing directory, and name it the given filename. but i'm getting an I/O error permission denied... what is wrong with this code?
import os
path = "C:/Users/CDGarcia/Desktop"
os.chdir(path)
gribs = os.listdir("testgrib")
print gribs
print os.getcwd()
if not os.path.exists(os.path.basename("gribs")):
os.makedirs(os.path.dirname("gribs"))
with open(path, "w") as f:
f.write("filename")
os.path.dirname() does not do what you expect it to do. It returns the directory name for the path you pass to it. So it interprets whatever string you pass as a path. As such, when you pass a path that has no directory part, it returns an empty string:
>>> os.path.dirname("gribs")
''
So with os.makedirs() you are trying to create an empty directory, which of course will not create the path you are looking for.
Instead, you should just use os.makedirs('gribs') to create gribs folder relative to your current directory.
Furthermore, open(path) will not work when path is the path to the desktop directory. You will have to pass a path to a file there. You probably meant to use a file path relative to the folder you create there:
with open('gribs/something.txt', 'w+') as f:
f.write('example content')

Categories