Here is what I try to do and I use windows and Python 3.3
LOG_FILENAME = 'log_trial_%s.txt' % datetime.datetime.now().strftime('%m%d-%H:%M:%S')
log_fd = open(LOG_FILENAME, 'w')
log_fd.write('===================\n')
The above codes are of course a part of a module and whe I ran the module, I got an error message as follows:
log_fd = open(LOG_FILENAME, 'w')
OSError: [Errno 22] Invalid argument: 'log_trial_1209-11:39:40.txt'
I have no idea what the long weird log finame means ('log_trial_%s.txt' ...) and how to fix the error thing as well.
I will appreciate your time and help.
Windows file names can't have colons in them.
Try this instead:
LOG_FILENAME = 'log_trial_%s.txt' % datetime.datetime.now().strftime('%m%d-%H%M%S')
Related
I'm getting the following error when I run my code (the error occurs at the *** line):
Exception has occurred: PermissionError
[WinError 32] The process cannot access the file because it is being used by another process: 'pexels-joshua-woroniecki-9073157.mp4' #this file is one of two files found in my stockFootage directory
I'm trying to delete a file, but it's telling me I got a permission error. Does anyone know how I could fix this? Any help would be greatly appreciated. Thank you.
My Code:
chdir(r'C:\Users\jack_l\Documents\REDDIT_TO_YOUTUBE_PYTHON_SELENIUM\redditVideo\stockFootage')
myStockFootage = next(walk(r'C:\Users\jack_l\Documents\REDDIT_TO_YOUTUBE_PYTHON_SELENIUM\redditVideo\stockFootage'), (None, None, []))[2]
stockFootage = VideoFileClip(myStockFootage[0], target_resolution=(1080, 1920))
stockFootage = stockFootage.without_audio()
stockFootage = stockFootage.loop(duration = mergedVideos.duration)
stockFootage.write_videofile('loopedStock.mp4', fps = 30)
for counter24 in range(len(myStockFootage)):
if 'loopedStock' not in myStockFootage[counter24]:
*** os.remove(myStockFootage[counter24])
chdir(r'C:\Users\jack_l\Documents\REDDIT_TO_YOUTUBE_PYTHON_SELENIUM\redditVideo\finalVideo')
finalVideo = CompositeVideoClip([stockFootage, commentVideo])
finalVideo.write_videofile('finalVideo.mp4', fps=30)
print('Finished')
From the comments it is clear that you're either not sharing the code causing the actual problem, or making more changes than was suggested in the comments.
Take this:
from shutil import copy
from os import remove
import moviepy.video.io.VideoFileClip as VideoFileClip
copy('test.mp4', 'new_test.mp4')
stock_footage = VideoFileClip.VideoFileClip(r'new_test.mp4', target_resolution=(1080, 1920))
try:
remove('new_test.mp4')
except PermissionError:
print('as expected')
stock_footage .close()
try:
remove('new_test.mp4')
print('success')
except PermissionError:
print('you will not see this')
Output (assuming you have a test.mp4 in the same location as the script):
as expected
success
Which shows that VideoFileClip locks the file it opens and calling .close() on it resolves the issue.
I am trying to access a test text file on a server with the command os.startfile but I can't seem to make it work. I know it only fails because the text file is on the server and not on the computer but I have no idea how to access it.
Here's my code :
from os import startfile
path = "//10.2.30.61/c$/Qlikview_Tropal/Raport/test1.txt"
startfile("//10.00.00.00/c$/test/test1/test1.txt")
And I get this error : FileNotFoundError: [WinError 2]. I am on windows by the way.
Update_1 : I tried the enter os.startfile(os.path.normpath()) and i get this error : "filenotfounderror winerror 53 the network path was not found"
Thank you !!
You can do
from os import start file
#put two \\ to get one \
path = "\\\\10.2.30.61\\c$\\Qlikview_Tropal\\Raport\\test1.txt"
startfile(r"\\10.00.00.00\c$\test\test1\test1.txt")
https://stackoverflow.com/a/43205543/14579156
Here is the code I've got:
filename = 'C:\\Users\chnyr\Desktop\Python Programs'
var = [i for i in open(filename, 'r+')]
['1\n', '2\n', '3\n', '\n']
I keep getting an error message below. I am using pyCharm v3.8.
C:\Users\chnyr\anaconda3\envs\untitled3\python.exe "C:/Users/chnyr/PycharmProjects/untitled3/translate test.py"
Traceback (most recent call last):
File "C:/Users/chnyr/PycharmProjects/untitled3/translate test.py", line 9, in <module>
var = [i for i in open('C:\\Users\chnyr\Desktop\Python Programs', 'r+')]
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\chnyr\\Desktop\\Python Programs'
Process finished with exit code 1
You get the error is you are trying to open a folder using the open() method. You can only open files with the method.
In python (and a lot of other languages) \ is the escape character.This makes coding with windows filesystems rather tricky. You have to escape each escape, by doing \\ instead of\. Aside from this, like Ann zen said, open only works with files. What you probably want is glob.glob, from the glob module.
import glob
var = [i for i in glob.glob('C:\\Users\\chnyr\\Desktop\\Python Programs\\*.py')]
print(var)
a = []
for i in var:
a.append(open(i,'r+'))
Running some code with Python3 reports the below error:
$ python3 report.py --regions ap-southeast-2 --file file.csv
File "report.py", line 51
except Exception, e:
^
SyntaxError: invalid syntax
Research indicates that this deprecated syntax. I have found conflicting information on how I may fix this.
I have tried to engage python3 syntax, which I believe would be to switch
try:
f = file(filepath, 'wt')
except Exception, e:
f = None
sys.stderr.write ('Could not open file %s. reason: %s\n' % (filepath, e))
To:
try:
f = file(filepath, 'wt')
except:
f = None
sys.stderr.write ('Could not open file %s. reason: %s\n' % (filepath, e))
What happens then is that I get errors relating to the "e" being missing... so I'm unsure how best and easiest to resolve the syntax issues between the two versions. Can you help or advise? Thanks!
If you really want a method that is compatible for both Python2 and Python3,
Then try something like this:
import sys
try:
### your filepath code goes here or any other code
except Exception:
tb, err = sys.exc_info()[:2]
print(err)
Using exc_info() here is good as it provides you with a tuple of information on what the error and the traceback to that faulting code, specifically the (type, value, traceback). In this case, you are getting back the traceback and the error (value).
I have custom python library installed on my NAS which has this code:
try:
i = open("/volume1/web/python/session.txt")
try:
a = str(i.read())
except Exception as err:
a = "Exception: {0}".format(err)
finally:
i.close()
except Exception as err:
a = "Exception: {0}".format(err)
return a
This code is invoked by app.py which saves returned text to file.
When app.py is run from SSH, it saves the content of session.txt as intended.
But when app.py is run as task (run.sh), it saves exception "'ascii' codec can't decode byte 0xc3 in position 12: ordinal not in range(128)". Yeah, the file contains "รก" in position 12, so I add encoding="utf-8" to open() function. And this fails (does not save anything, so I don't even know if and what error it threw.)
QUESTION
Any ideas how to safely open and read text file by python library (when by regular script, runs correctly even if it is run as task)?
FILES involved
library:
class API():
def __init__(self, dir):
self.DIR = dir
def CheckTokens(self):
print("\nChecking all saved tokens")
try:
i = open(os.path.join(self.DIR, "session.txt"), encoding='utf-8')
try:
a = i.read()
except Exception as err:
a = "Exception: {0}".format(err)
finally:
i.close()
except Exception as err:
a = "Exception: {0}".format(err)
return a
app.py:
import os.path
from time import localtime, strftime
from APIfile import API
if __name__ == "__main__":
LOCAL_DIR = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
def write(text, type):
time = localtime()
time = "%s#%s" % (strftime("%Y%m%d", time), strftime("%H%M%S", time))
filename = "%s%s.txt" % (time, ("_%s" % type if type != "JSON" else ""))
f = open(os.path.join(LOCAL_DIR, "logs", filename), "a")
f.write(str(text))
f.close()
INSTANCE = API(LOCAL_DIR)
tokens = INSTANCE.CheckTokens()
write(tokens, "DEBUG")
run.sh:
python3 /volume1/web/python/app.py
session.txt and logs folder is located in the same directory as app.py
OUTCOMES
Run from SSH python3 /volume1/web/python/app.py -> saves content of session.txt to log file
Run from SSH /volume1/web/python/run.sh -> does the same as 1.
Run run.sh file as task (something like cron job) -> does not create log file
When I remove encoding='utf-8' statement from open function, in SSH run correctly, in task throws an exception ('ascii' codec can't decode byte 0xc3 in position 12: ordinal not in range(128))
I'm a little puzzled, but here's my guess: open() defaults to the shell's preferred encoding, and your NAS's locale is somehow set differently than your local shell's. I think that encoding=utf-8 is the fix for your current issue.
Now, you say that doesn't work either. I'm not sure what you mean by "does not save anything" -- my guess here is that your script needs to save its output to a file, and the NAS daemon doesn't have permissions to write to that file. You don't say what the call responsible for the saving to disk actually looks like, but I believe that's a separate issue from the problem with your encoding.