Someone created an awesome script to download videos for personal use which is permitted under their TOS. However when the script tries to create a directory based on the title name, it creates an error due to a question mark "?" in the title. Windows does not permit special characters in the directory name. Is there a way to tell makedirs to ignore special character?
Traceback (most recent call last):
File "D:\nick.py", line 91, in <module>
main()
File "D:\nick.py", line 88, in main
episode.download()
File "D:\nick.py", line 37, in download
os.makedirs(dirname)
File "C:\Users\*****\AppData\Local\Programs\Python\Python38\lib\os.py", line 223, in makedirs
mkdir(name, mode)
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: "The Crystal Maze\\What's The Sign For Winning?"
You can remove the symbols using this line:
''.join([i for i in name if i.isalnum() or i.isspace()])
You'll have to change dirname in the source code for what I wrote above:
os.makedirs(dirname) # in line 37, in download
It will save as the name, but without the symbols:
Out[58]: 'The Crystal Maze Whats The Sign For Winning'
Related
I have this code :
import gensim
filename = 'GoogleNews-vectors-negative300.bin'
model = gensim.models.KeyedVectors.load_word2vec_format(filename, binary=True)
and this is my folder organization thing :
image of my folder tree that shows that the .bin file is in the same directory as the file calling it, the file being ai_functions
But sadly I'm not sure why I'm having an error saying that it can't find it. Btw I checked, I am sure the file is not corrupted. Any thoughts?
Full traceback :
File "/Users/Ile-Maurice/Desktop/Flask/flaskapp/run.py", line 1, in <module>
from serv import app
File "/Users/Ile-Maurice/Desktop/Flask/flaskapp/serv/__init__.py", line 13, in <module>
from serv import routes
File "/Users/Ile-Maurice/Desktop/Flask/flaskapp/serv/routes.py", line 7, in <module>
from serv.ai_functions import checkplagiarism
File "/Users/Ile-Maurice/Desktop/Flask/flaskapp/serv/ai_functions.py", line 31, in <module>
model = gensim.models.KeyedVectors.load_word2vec_format(filename, binary=True)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/gensim/models/keyedvectors.py", line 1629, in load_word2vec_format
return _load_word2vec_format(
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/gensim/models/keyedvectors.py", line 1955, in _load_word2vec_format
with utils.open(fname, 'rb') as fin:
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/smart_open/smart_open_lib.py", line 188, in open
fobj = _shortcut_open(
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/smart_open/smart_open_lib.py", line 361, in _shortcut_open
return _builtin_open(local_path, mode, buffering=buffering, **open_kwargs)
FileNotFoundError: [Errno 2] No such file or directory: 'GoogleNews-vectors-negative300.bin'
The 'current working directory' that the Python process will consider active, and thus will use as the expected location for your plain relative filename GoogleNews-vectors-negative300.bin, will depend on how you launched Flask.
You could print out the directory to be sure – see some ways at How do you properly determine the current script directory? – but I suspect it may just be the /Users/Ile-Maurice/Desktop/Flask/flaskapp/ directory.
If so, you could relatively-reference your file with the path relative to the above directory...
serv/GoogleNews-vectors-negative300.bin
...or you could use a full 'absolute' path...
/Users/Ile-Maurice/Desktop/Flask/flaskapp/serv/GoogleNews-vectors-negative300.bin
...or you could move the file up to its parent directory, so that it is alonside your Flask run.py.
Python code:
import tarfile,os
import sys
def extract_system_report (tar_file_path):
extract_path = ""
tar = tarfile.open(sys.argv[1])
for member in tar.getmembers():
print ("member_name is: ")
print (member.name)
tar.extract(member.name, "./crachinfo/")
extract_system_report(sys.argv[1])
while extracting the file getting below error:
>> python tar_read.py /nobackup/deepakhe/POLARIS_POJECT_09102019/hackathon_2021/a.tar.gz
member_name is:
/bootflash/.prst_sync/reload_info
Traceback (most recent call last):
File "tar_read.py", line 38, in <module>
extract_system_report(sys.argv[1])
File "tar_read.py", line 10, in extract_system_report
tar.extract(member.name, "./crachinfo/")
File "/auto/pysw/cel8x/python64/3.6.10/lib/python3.6/tarfile.py", line 2052, in extract
numeric_owner=numeric_owner)
File "/auto/pysw/cel8x/python64/3.6.10/lib/python3.6/tarfile.py", line 2114, in _extract_member
os.makedirs(upperdirs)
File "/auto/pysw/cel8x/python64/3.6.10/lib/python3.6/os.py", line 210, in makedirs
makedirs(head, mode, exist_ok)
File "/auto/pysw/cel8x/python64/3.6.10/lib/python3.6/os.py", line 220, in makedirs
mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: '/bootflash'
I am specifying the folder to extract but still it seems trying to create a folder in the root directory. is this behavior expected? I can extract this tar file fine in file manager. is there a way to handle this in python?
I am specifying the folder to extract but still it seems trying to create a folder in the root directory. is this behavior expected?
Yes. The path provided is just a "current directory", it's not a "jail". The documentation even specifically warns about it:
It is possible that files are created outside of path, e.g. members that have absolute filenames starting with "/" or filenames with two dots "..".
I can extract this tar file fine in file manager. is there a way to handle this in python?
Use extractfile to get a pseudo-file handle on the contents of the archived file, then copy that wherever you want.
I found these two pages:
Subprocess.run() cannot find path
Python3 Subprocess.run cannot find relative referenced file
but it didn't help. The first page talks about using \\ but I already do, and the second one talks about double quotes around one of the arguments.
work = Path("R:\\Work")
resume = work.joinpath("cover_letter_resume_base.doc")
current_date = construct_current_date()
company_name = gather_user_information(question="Company name: ",
error_message="Company name cannot be empty")
position = gather_user_information(question="Position: ",
error_message="Position cannot be empty")
# Construct destination folder string using the company name, job title, and current date
destination = work.joinpath(company_name).joinpath(position).joinpath(current_date)
# Create the destintion folder
os.makedirs(destination, exist_ok=True)
# Construct file name
company_name_position = "{0}_{1}{2}".format(company_name.strip().lower().replace(" ", "_"),
position.strip().lower().replace(" ", "_"), resume.suffix)
resume_with_company_name_job_title = resume.stem.replace("base", company_name_position)
destination_file = destination.joinpath(resume_with_company_name_job_title)
# Copy and rename the resume based on the company and title.
shutil.copy2(src=resume, dst=destination_file)
if destination_file.exists():
print(f"{destination_file} created.")
#subprocess.run(["open", str(destination_file)], check=True)
The program gets the company name and position from the user, generates the current date, creates the directories, and then moves/renames the base resume based on the user input.
Output and Results:
Company name: Microsoft
Position: Software Eng
R:\Work\Microsoft\Software Engineer\20190722\cover_letter_resume_microsoft_software_eng.doc
created.
Error Message:
[WinError 2] The system cannot find the file specified
Traceback (most recent call last):
File "c:/Users/Kiska/python/job-application/main.py", line 59, in <module>
main()
File "c:/Users/Kiska/python/job-application/main.py", line 53, in main
raise error
File "c:/Users/Kiska/python/job-application/main.py", line 48, in main
subprocess.run(["start", str(destination_file)], check=True)
File "C:\Program Files (x86)\Python37-32\lib\subprocess.py", line 472, in run
with Popen(*popenargs, **kwargs) as process:
File "C:\Program Files (x86)\Python37-32\lib\subprocess.py", line 775, in __init__
restore_signals, start_new_session)
File "C:\Program Files (x86)\Python37-32\lib\subprocess.py", line 1178, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
The if statement returns True but subprocess.run() cannot see the file, but I'm not really sure why.
On which operating system are you? The backslashes in your path suggest that you're on Windows and you're using open to open the document with its default application. However, looking at this question Open document with default OS application in Python, both in Windows and Mac OS you should use start instead of open for Windows:
subprocess.run(["start", str(destination_file)], check=True, shell=True)
Also you need to add shell=True for start to work. However, you should read https://docs.python.org/3/library/subprocess.html#security-considerations beforehand.
(I suspect, the error [WinError 2] The system cannot find the file specified appears, because Windows cannot find open - it's not about the document you're trying to open.)
I wrote this program to move videos from my download folder to different destination folders.
import os
import shutil
import sys
folder = []
highlight = ['highlights','goals','skills']
comedy_word = ['comedy', 'acapella','seyilaw','basketmouth','basket mouth','bovi','gordons','buchi','rhythm unplugged','elenu','seyi law','akpororo','emmaohmygod','klint','shakara','funnybone','igodye','i go die','i go dye','igodye','whalemouth','whale mouth','daniel']
series_word = ['lost', 'thrones', 'vampire', 'originals', 'ship', '']
grub_word = ['programming', 'python', 'linux','exploit','hack']
for i in os.listdir('C:\\Users\\Afro\\Downloads\\Video'):
folder.append(i.lower())
def tv_series(series):
for serie in series:
if 'ship' in serie:
shutil.move(serie, 'C:\\Users\\Afro\\Desktop\\Movies\\Series\\The Last Ship\\The Last Ship 3\\' )
print(serie[:-3] +': Moved!')
elif 'lost' in serie:
shutil.move(serie, 'C:\\Users\\Afro\\Desktop\\Movies\\Series\\Lost\\s2\\' )
print(serie[:-3] +': Moved!')
The file's name is arrange.py and the program throws a filenotfound error when arrange.py is not in the "C:\Users\Afro\Downloads\Video" folder. Is it possible to make the program run in any folder?
Thanks
Here's the error it throws.
Traceback (most recent call last):
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 538, in move
os.rename(src, real_dst)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'lost - s02e08 (o2tvseries.com).mp4' -> 'C:\\Users\\Afro\\Desktop\\Movies\\Series\\Lost\\s2\\lost - s02e08 (o2tvseries.com).mp4'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Afro\Desktop\Arrange.py", line 77, in <module>
start(folder)
File "C:\Users\Afro\Desktop\Arrange.py", line 65, in start
tv_series(folder)
File "C:\Users\Afro\Desktop\Arrange.py", line 22, in tv_series
shutil.move(serie, 'C:\\Users\\Afro\\Desktop\\Movies\\Series\\Lost\\s2\\' )
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 552, in move
copy_function(src, real_dst)
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 251, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 114, in copyfile
with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'lost - s02e08 (o2tvseries.com).mp4'
You call shutil.move specifying the reference point incorrectly. In your loop that gathers the files, you should use os.path.join('C:\\Users\\Afro\\Downloads\\Video', i) and put that in your list instead. Otherwise it's all relative paths, hence the FileNotFound error.
You could also change the working directory. This would make the script behave as if it was in a different folder. This can have some unintended consequences, so be careful. Details here.
Hope this helps!
I'm getting a permission error when trying to save a screenshot from Sikuli under Windows. The code that's doing the capturing is:
def CaptureScreenshot(self):
resultsDirectory = os.path.join('C','08 May 2013 11 34','myname.png')
screenshot = capture(self.screen)
print(screenshot)
shutil.move(screenshot,self.resultsDirectory)
When I print the screenshot path returned by capture, I get
D:\DOCUME~1\BUNNINGS\LOCALS~1\Temp\sikuli-scr-366782306192033926.png
When I run the code, I get this error:
Traceback (most recent call last):
File "__pyclasspath__/Tests/Tests.py", line 12, in tearDown
File "__pyclasspath__/Scripts/Screen.py", line 39, in CaptureScreenshot
File "C:\jython2.5.3\Lib\shutil.py", line 205, in move
copy2(src,dst)
File "C:\jython2.5.3\Lib\shutil.py", line 96, in copy2
copyfile(src, dst)
File "C:\jython2.5.3\Lib\shutil.py", line 52, in copyfile
fdst = open(dst, 'wb')
IOError: [Errno 13] Permission denied: 'C\\08 May 2013 11 34\\myname.png'
The destination folder exists and myname.png is the new name I am trying to give to the image.
I noticed that the destination folder's properties are set to "read only". Is this causing the issue? I couldn't change the readonly attribute; when I try, it just goes back to readonly.
There seems to be a colon missing after the C in your path. You are now trying to write in a subdirectory 'C' of the current directory.
Try to change the second line into:
resultsDirectory = os.path.join('C:','08 May 2013 11 34','myname.png')
^