How can I open a folder with argparse - python

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.

Related

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.

Looping for files in a directory, but cannot open the files in the directory because it doesn't exist

I was trying to read data from a bunch of textfiles in a directory, but getting an error while opening the file
import os
fileList = os.listdir("Desktop/SLUI")
for txtName in fileList:
#Open the textfile
UIname=str(txtName)
userDTL=open(UIname,'r')
if userDTL.mode=='r':
line=userDTL.readlines()
string1=line[0]
string2=line[1]
string3=line[2]
UserDTL.close()
print(string1)
Here is the error when I try to run this code via cmd.exe
File "C:\Users\*****\Desktop\programName.py", line 24, in <module>
userDTL=open(UIname,'r')
FileNotFoundError: [Errno 2] No such file or directory: 'file1.txt'
It's because os.listdir only displays the name of the files, and to open them you need the whole path.
You need to redefine UIname as such:
UIname=os.path.join("Desktop/SLUI",txtName) # I don't think you need the string conversion.
os.path.join() will properly join two (or more) bits of paths, whichever OS you use.
I'm not really familiar with how Python works on Windows, so you might need to replace "Desktop/SLUI" by the appropriate path to your desktop (C:\Users*****\Desktop).

Python save file to root subfolder

I am trying to set the folder_out to the subfolder where the source .csv is found.
So I have many folders and subfolders in the main Processing folder.
I want to save the the .csv file in the same folder as where it has found the file.
When I use the root, with pathlib, is that possible?
And, I am getting now back IOError: [Errno 13] Permission denied: 'D:\Processing\DG_Boeblingen-..... etc.
So it found the file, but can't write.
I am in Python 2.7 and using 'wb' to write.
how I set the Path and rb an wb, is using wb and rb, correct?
folder_in = Path(r'D:\Processing')
folder_out = Path(r'.')
folder_in_traj = Path(r'D:\Processing')
folder_out_traj = Path(r'.')
for incsv in folder_in.iterdir():
outcsv = folder_out.joinpath('0new'+incsv.name)
with open(str(incsv), 'rb') as input, open(str(outcsv), 'wb') as output:
You are trying to save a file in root directory for which you would need sudo prviliges so if you execute the python script as super user then you should not see this issue.
I am kind of confused as to what you are trying to do here. Are you trying to output the CSV to root? In that case I think you are using Path(r'root') wrong. If you look at the documentation for pathlib, there is a class called PurePath with a method called root. You can use this to return the root.
Passing in root to Path will just return root as the path. You can try using . instead of root which might resolve to the root.

Python - Errno 13 Permission denied when trying to copy files

I am attempting to make a program in Python that copies the files on my flash drive (letter D:) to a folder on my hard drive but am getting a PermissionError: [Errno 13] Permission denied: 'D:'.
The problematic part of my code is as follows:
# Copy files to folder in current directory
def copy():
source = getsource()
if source != "failure":
copyfile(source, createfolder())
wait("Successfully backup up drive"
"\nPress 'Enter' to exit the program")
else:
wait("No USB drive was detected"
"\nPress 'Enter' to exit")
# Create a folder in current directory w/ date and time
def createfolder():
name = strftime("%a, %b %d, %Y, %H.%M.%S", gmtime())
dir_path = os.path.dirname(os.path.realpath(__file__))
new_folder = dir_path + "\\" + name
os.makedirs(new_folder)
return new_folder
Everything seems to run fine until the copyfile() function runs, where it returns the error.
I tried replacing getsource() with the destination of the file instead and it returned the same permission error except for the new_folder directory instead.
I have read several other posts but none of them seem to be relevant to my case. I have full admin permissions to both locations as well.
Any help would be greatly appreciated!
As I stated in my comment above, it seems as if you're trying to open the directory, D:, as if it was a file, and that's not going to work because it's not a file, it's a directory.
What you can do is use os.listdir() to list all of the files within your desired directory, and then use shutil.copy() to copy the files as you please.
Here is the documentation for each of those:
os.listdir() (You will be passing the full file path to this function)
shutil.copy() (You will be passing each file to this function)
Essentially you would store all of the files in the directory in a variable, such as all_the_files = os.listdir(/path/to/file), then loop through all_the_files by doing something like for each_file in all_the_files: and then use shutil.copy() to copy them as you please.
If you're looking to copy an entire directory and its contents, then shutil.copytree(source, destination) can be used.

Python creating directory gives IO error

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

Categories