How do I find a filename starting with "dec2💜file" that has an extension on OSX?
In my case, I have only one .ppt file in the Documents directory. So, the result should be:
dec2💜file.ppt
Here is the code:
my_pathname='Documents'
my_filename='dec2💜file'
my_glob = "{c}.{ext}".format(c=my_filename, ext='*')
try:
my_filename = str(list(pathlib.Path(my_pathname).glob(my_glob))[0])
except Exception as ex:
print("Error - {d}/{f} - {e}".format(d=my_pathname, f=my_glob, e=str(ex)))
exit(1)
print("Found it - {f}".format(f=my_filename))
Current result:
ERROR - Documents/dec2💜file.* - list index out of range
How do I get it to find the file and print:
Found it - dec2💜file.ppt
After creating a folder called test, and a file inside it called dec2💜file.txt, I ran this:
import pathlib
my_pathname = 'test'
my_filename = 'dec2💜file'
my_glob = "{c}.{ext}".format(c=my_filename, ext='*')
try:
my_filename = str(list(pathlib.Path(my_pathname).glob(my_glob))[0])
except Exception as ex:
print("Error - {d}/{f} - {e}".format(d=my_pathname, f=my_glob, e=str(ex)))
exit(1)
print("Found it - {f}".format(f=my_filename))
And got:
Found it - test\dec2💜file.txt
So, I can only conclude there is no folder called Documents inside the working directory where your script runs. Try replacing my_pathname with a full path name, or ensure your script runs in the parent directory of Documents.
You can do this by either changing the working directory of the script from your IDE or on the command line, or by using os.chdir or something similar to change directory before the relevant part of the script.
Related
So I am fairly new with coding in Python and in general and I am trying to write a program that will backup files in a giving folder. However, I continue to get a "NameError: name 'src' is not defined. I see some other questions similar about this error but none have yet to make me understand what I am doing wrong or why I get this error. As far as I understand it I am defining 'src' in the code below. Any help would be greatly appreciated.
ERROR:
File "/home/student/PycharmProjects/Lab1.py/Lab5.5.py", line 1, in processing
backup(src, dest)
NameError: name 'src' is not defined
def backup(src, dest):
#Checking if src and dest directories exist
sourceFilePath = input('Enter folder path to be backed up')
destFilePath = input('Please choose where you want to place the backup')
#found = true
for directory in [src, dest]:
if not isdir(directory):
print(f'could not find {directory}')
found = False
if not found:
exit(1)
#for each file in src
for sourceFileName in listdir(src):
#computing file paths
sourceFilePath = path.join(src, sourceFileName)
destFilePath = path.join(dest, sourceFileName)
#backing up file
copy2(sourceFilePath, destFilePath)
#entry point
if __name__=='__main__':
#validating length of command line arguments
if len(argv) != 3:
print(f'Usage: {argv[0]} SRC DEST')
exit(1)
#performing backup
backup(argv[1], argv[2])
#logging status message
print('Backup succesful!')
why are you prompting the user for src and dest path though you already pass them as command args? The issue probably came from the fact you didn't provide the src arg while running the script. Things like
python script.py srcpath dstpath
I've just started experimenting with flask and
I am trying to list a network driver using it. This is the command that I type on my browser. But I get an error that it cant find the path
http://127.0.0.1:5000/130.13.5.8/D/dir/
The function works for local drivers without an issue
I know why it fails. It needs 2 '\' before the actual ip or 4 '\\' .
But when I try http://127.0.0.1:5000/////130.13.5.8/D/dir/
it doesnt work.
I even tried %F%F it also doesn't seem to do the trick.
#app.route('/<path:filepath>/dir/')
def get_dir(filepath):
dir_listing = ''
for entry in os.listdir(filepath):
entry_type = 'dir' if os.path.isdir(os.path.join(filepath, entry)) else 'file'
dir_listing += '{entry_name}|{entry_type}|'.format(entry_name=entry, entry_type=entry_type)
return dir_listing
For anyone having the same issue my workaround is the following
from ipaddress import ip_address
try:
ip_address(filepath.split('/')[0])
filepath = '\\\\{filepath}'.format(filepath=filepath)
except ValueError as e:
pass
I'm creating a really basic program that simulates a terminal with Python3.6, its name is Prosser(The origin is that "Prosser" sounds like "Processer" and Prosser is a command processer).
A problem that I'm having is with command import, this is, all the commands are stored in a folder called "lib" in the root folder of Prosser and inside it can have folders and files, if a folder is in the "lib" dir it can't be named as folder anymore, its name now is package(But this doesn't care for now).
The interface of the program is just a input writed:
Prosser:/home/pedro/documents/projects/prosser/-!
and the user can type a command before the text, like a normal terminal:
Prosser:/home/pedro/documents/projects/prosser/-! console.write Hello World
let's say that inside the "lib" folder exists one folder called "console" and inside it has a file called "write.py" that has the code:
class exec:
def main(args):
print(args)
As you can see the first 2 lines is like a important structure for command execution: The class "exec" is the main class for the command execution and the def "main" is the main and first function that the terminal will read and execute also pass the arguments that the user defined, after that the command will be responsible to catch any error and do what it will be created to do.
At this moment, everything is ok, but now comes the true help that I need of U guys, the command import.
Like I writed the user can type any command, and in the example above I typed a "console.write Hello World" and exists one folder called "console" and one file "write.py". The point is that the packages can be defined by a "dot", this is:
-! write Hello World
Above I only typed "write" and this says that the file is only inside the "lib" folder, it doesn't has a package to storage and separate it, so it is a Freedom command(A command that doesn't has packages or nodes).
-! console.write Hello World
Now I typed above "console.write" and this says that the file has a package or node to storage and separate it, this means that it is a Tied command(A command that has packages or nodes).
With that, a file is separated from the package(s) with a dot, the more dots you put, more folders will be navigated to find the file and proceed to the next execution.
Code
Finnaly the code. With the import statement I tryied this:
import os
import form
curDir = os.path.dirname(os.path.abspath(__file__)) # Returns the current direrctory open
while __name__ == "__main__":
c = input('Prosser:%s-! ' % (os.getcwd())).split() # Think the user typed "task.kill"
path = c[0].split('.') # Returns a list like: ["task", "kill"]
try:
args = c[1:] # Try get the command arguments
format = form.formater(args) # Just a text formatation like create a new line with "$n"
except:
args = None # If no arguments the args will just turn the None var type
pass
if os.path.exists(curDir + "/lib/" + "/".join(path) + ".py"): # If curDir+/lib/task/kill.py exists
module = __import__("lib." + '.'.join(path)) # Returns "lib.task.kill"
module.exec.main(args) # Execute the "exec" class and the def "**main**"
else:
pathlast = path[-1] # Get the last item, in this case "kill"
path.remove(path[-1]) # Remove the last item, "kill"
print('Error: Unknow command: ' + '.'.join(path) + '. >>' + pathlast + '<<') # Returns an error message like: "Error: Unknow command: task. >>kill<<"
# Reset the input interface
The problem is that when the line "module = __import__("lib." + '.'.join(path))" is executed the console prints the error:
Traceback (most recent call last):
File "/home/pedro/documents/projects/prosser/main.py", line 18, in <module>
module.exec.main(path) # Execute the "exec" class and the def "**main**"
AttributeError: module 'lib' has no attribute 'exec'
I also tried to use:
module = \_\_import\_\_(curDir + "lib." + '.'.join(path))
But it gets the same error. I think it's lighter for now. I'd like if someone help me or find some replacement of the code. :)
I think you have error here:
You have diffirent path here:
if os.path.exists(curDir + "/lib/" + "/".join(path) + ".py")
And another here, you dont have curDir:
module = __import__("lib." + '.'.join(path)) # Returns "lib.task.kill"
You should use os.path.join to build paths like this:
module = __import__(os.path.join(curdir, 'lib', path + '.py'))
Solved: Adding an os.chdir(myArg) resolved the issue.
I'm getting an error when trying to run the following code on anything other than my home directory or files/direcs that I own.
FileNotFoundError: [Errno 2] No such file or directory:
I created a file in root and changed ownership on the file to pi:pi (user running the script). If I specify that file directly, it works, however if I run the script on "/", it will not read that or any other file/direc. I also created a directory /tempdir_delete/ and changed ownership to pi:pi.. If I run the script specifically on "/tempdir_delete/*", it works, but if I leave off the * it fails.
Why does it fail on all except /home/pi/ or files that I explicitly specify and own? It's running the stat as user pi, which is granted by sudo to perform the stat. Also, why do I have to specify the file that I own explicitly? Shouldn't it see that file in root and work because I own it?
import os
import re
import sys
import pwd
myReg = re.compile(r'^\.')
myUID = os.getuid()
myArg = sys.argv[1]
print(os.getuid())
print(pwd.getpwuid(int(myUID)))
print(myArg)
def getsize(direct):
if os.path.isfile(direct) == True:
statinfo = os.stat(myArg)
print(str(statinfo.st_size))
else:
for i in os.listdir(direct):
try:
statinfo = os.stat(i)
if myReg.search(i):
continue
else:
print(i + ' Size: ' + str(statinfo.st_size))
except:
print('Exception occurred, can't read.')
continue
getsize(myArg)
Solved. Adding an os.chdir(myArg) worked to resolve the issue.
In the following piece of code, some_path is a string that corresponds to a path (may be a relative path)
def editable(some_path):
"""Safely check whether a file is editable."""
delete = not os.path.exists(some_path)
try:
with open(some_path, 'ab'):
return True
except:
return False
finally:
# If the file didn't exist before, remove the created version
if delete:
try:
os.remove(some_path)
except:
pass
In open's docs we read:
If the file cannot be opened, IOError is raised
Is IOError the only possible error I can get (UnicodeError comes to mind, or OSError etc) ?
os.remove docs are even more vague:
If path is a directory, OSError is raised
So what if the file is in use, or protected or...
UPDATE: How about shutil.move ? This seems to raise yet another shutil.Error(StandardError) - if I read the source right