Trying to resolve the issue But no luck yet. Can some body tell me what's the issue. Tried re indenting the code.
I am not able to print the File Not found text in the exception block in the code.
Is this the indentation issue ?
Code Snippet:
from xlutils.copy import copy
from xlrd import open_workbook
import xlwt
import os
import shutil
import glob
def openexcel_main():
book = open_workbook('input.xls',formatting_info=True)
sheet = book.sheet_by_index(0)
wb = copy(book)
w_sheet = wb.get_sheet(0)
folder_name=['do_not_delete','internal_builds']
for j in range (0,2):
folder=folder_name.pop()
for i in range (1,(sheet.nrows)):
cell_test_group = sheet.cell(i,0)
data=str(cell_test_group.value)
print '#####################################'
print data
list=[]
source_path='/mnt/'+folder+'/pybuild/'+data+'/MAIN/'
if os.path.exists(source_path):
try:
os.chdir(source_path)
all_subdirs = [d for d in os.listdir('.') if os.path.isdir(d)]
for dirs in all_subdirs:
dir = os.path.join('/mnt/'+folder+'/pybuild/'+data+'/MAIN/', dirs)
os.chdir(dir)
current = os.getcwd()
new = str(current).split("/")[6]
list.append(new)
list.sort()
val=list
for i in range (1,4):
if val==[]:
break
else:
print i
current_build_number=val.pop()
print 'Current_Build:'+current_build_number
source_path_copy = r""+ source_path+"/"+current_build_number+"/"
print 'Copying From:'+ source_path_copy
dest_path = r"/home/builds_repo/"+folder+"/pybuild/"+data+"/MAIN/"+current_build_number+"/"
os.chdir(source_path_copy)
file_name=(glob.glob('*[_bin].*')).pop()
print 'File_Copied:'+ file_name
if not os.path.exists(dest_path):
os.makedirs(dest_path)
shutil.copyfile(source_path_copy + file_name, dest_path + file_name)
except:
print'File Not Found ..'
raise
def main():
openexcel_main()
main()
Try some good editors like pyscripter ,Emacs to make your pythonic life easy :)
I have tried to intend your code ...
from xlutils.copy import copy
from xlrd import open_workbook
import xlwt
import os
import shutil
import glob
def openexcel_main():
book = open_workbook('input.xls',formatting_info=True)
sheet = book.sheet_by_index(0)
wb = copy(book)
w_sheet = wb.get_sheet(0)
folder_name=['do_not_delete','internal_builds']
for j in range (0,2):
folder=folder_name.pop()
for i in range (1,(sheet.nrows)):
cell_test_group = sheet.cell(i,0)
data=str(cell_test_group.value)
print '#####################################'
print data
list=[]
source_path='/mnt/'+folder+'/pybuild/'+data+'/MAIN/'
if os.path.exists(source_path):
try:
os.chdir(source_path)
all_subdirs = [d for d in os.listdir('.') if os.path.isdir(d)]
for dirs in all_subdirs:
dir = os.path.join('/mnt/'+folder+'/pybuild/'+data+'/MAIN/', dirs)
os.chdir(dir)
current = os.getcwd()
new = str(current).split("/")[6]
list.append(new)
list.sort()
val=list
for i in range (1,4):
if val==[]:
break
else:
print i
current_build_number=val.pop()
print 'Current_Build:'+current_build_number
source_path_copy = r""+ source_path+"/"+current_build_number+"/"
print 'Copying From:'+ source_path_copy
dest_path = r"/home/builds_repo/"+folder+"/pybuild/"+data+"/MAIN/"+current_build_number+"/"
os.chdir(source_path_copy)
file_name=(glob.glob('*[_bin].*')).pop()
print 'File_Copied:'+ file_name
if not os.path.exists(dest_path):
os.makedirs(dest_path)
shutil.copyfile(source_path_copy + file_name, dest_path + file_name)
except Exception ,e: #Use Exception if not sure which exception will raise
print'File Not Found ..',e
#raise
def main():
openexcel_main()
if __name__ == '__main__': #Use main
main()
Line:
print'File Not Found ..'
, should be in else loop of
os.path.exists(source_path):
to check and print source path is not exists
Related
I wrote a function can detect USB's path and can keep writing input to file while file path is correct, and read the file out when file incorrect, however seems my read file function isn't activate
import time
from usb.core import find
from usb.util import get_string
import usb.backend.libusb1
import re
import usb.core
import usb.util
import os
import numpy as np
import os.path
from os import path
import os
import subprocess
def get_USB_path():
try:
#use linus call by python
a = subprocess.check_output(['lsblk'])
# I split by "\n" cause that in erery line of str_a
str_a_splited = a.decode().split("\n")
# USB in linux usually in media file
USB_info = [s for s in str_a_splited if "/media/" in s]
found_path = []
for x in USB_info:
for s in x.split(" "):
if "/media/" in s:
found_path.append(s)
except Exception as e:
return "error in get_USB_path()"
return found_path
path_output = get_USB_path()
def File_write(User_path, user_content):
try:
error_info1 = ""
if (path.exists(file_path)) == True:
file = open(User_path , "a")
file.write("\n" + user_content)
file.close()
else:
error_info1 = "Path incorrect"
except Exception as e:
return "error in File_write()"
return error_info1
def File_read(input_file_path):
try:
with open(input_file_path) as f:
contents = f.read()
except Exception as e:
return "error in File_read()"
return contents
print("= = = = ")
print(path_output)
print(type(path_output))
while True:
file_path_indexNum = int(input("Enter your desire file path (ex:0,1,2....): "))
file_name = str(input("Enter your file name (ex:aaa.txt): "))
file_path = (str(path_output[file_path_indexNum]) +"/" + file_name)
added_data = str(input("type ur added data : "))
error_info1 = File_write(file_path, added_data)
if (path.exists(file_path)) == True:
correct_file_path = file_path
if len(path_output) < file_path_indexNum:
print("error path, shut down")
break
contents = File_read(correct_file_path)
print(contents)
here the error is fine that I simulate the scenario that when file write path is incorrect , then should activate file read, but seems read function is not run yet, here is the output -
= = = =
['/media/joy/DATA2', '/media/joy/DATA', '/media/joy/DATA1']
<class 'list'>
Enter your desire file path (ex:0,1,2....): 0
Enter your file name (ex:aaa.txt): aaa.txt
type ur added data : 65555555
Enter your desire file path (ex:0,1,2....): 0
Enter your file name (ex:aaa.txt): aaa.txt
type ur added data : 1313231313
Enter your desire file path (ex:0,1,2....): 6
Enter your file name (ex:aaa.txt): 3
Traceback (most recent call last):
File "/home/joy/fe_dir/damm.py", line 76, in <module>
file_path = (str(path_output[file_path_indexNum]) +"/" + file_name)
IndexError: list index out of range
move len(path_output) < file_path_indexNum before into file path, index like 999 ,ore than list can still return [ ] for file path
import time
from usb.core import find
from usb.util import get_string
import usb.backend.libusb1
import re
import usb.core
import usb.util
import os
import numpy as np
import os.path
from os import path
import os
import subprocess
def get_USB_path():
try:
#use linus call by python
a = subprocess.check_output(['lsblk'])
# I split by "\n" cause that in erery line of str_a
str_a_splited = a.decode().split("\n")
# USB in linux usually in media file
USB_info = [s for s in str_a_splited if "/media/" in s]
found_path = []
for x in USB_info:
for s in x.split(" "):
if "/media/" in s:
found_path.append(s)
except Exception as e:
return "error in get_USB_path()"
return found_path
path_output = get_USB_path()
def File_write(User_path, user_content):
try:
error_info1 = ""
if (path.exists(file_path)) == True:
file = open(User_path , "a")
file.write("\n" + user_content)
file.close()
else:
error_info1 = "Path incorrect"
except Exception as e:
return "error in File_write()"
return error_info1
def File_read(input_file_path):
try:
with open(input_file_path) as f:
contents = f.read()
except Exception as e:
return "error in File_read()"
return contents
print("= = = = ")
print(path_output)
print(type(path_output))
while True:
file_path_indexNum = int(input("Enter your desire file path (ex:0,1,2....): "))
file_name = str(input("Enter your file name (ex:aaa.txt): "))
if len(path_output) < file_path_indexNum:
print("error path, shut down")
break
file_path = (str(path_output[file_path_indexNum]) +"/" + file_name)
added_data = str(input("type ur added data : "))
error_info1 = File_write(file_path, added_data)
if (path.exists(file_path)) == True:
correct_file_path = file_path
contents = File_read(correct_file_path)
print(contents)
Looking to make the following code recurse through sub-folders.
It works as I want it to right now, but I'm having difficulty wrapping my head around recursing through subfolders with the same for/if statements I already have in place. More of a logic block, thanks in advance.
import os
import sys
from datetime import datetime
from pathlib import Path
#search through entire path given as parameter, recursive
runtimepath = sys.argv
currenttime = "output" + (str(datetime.now().strftime("%m-%d-%Y-%H%M") + ".txt"))
print ("File", currenttime, "being generated.")
output_file = open(os.path.join(runtimepath[1], currenttime), "w")
ext_list = [
"txt","webm","mkv","flv","vob","ogv","ogg","drc","gif","gifv","mng",
"avi","mts","m2ts","mov","qt","wmv","yuv","rm","rmvb","asf","amv","mp4","m4p","m4v",
"mpg","mp2","mpeg","mpe","mpv","m2v","svi","3gp","3g2","mxf","roq","nsv","flv","f4v",
"f4p","f4a","f4b","mp3"
]
for f in os.listdir(runtimepath[1]) :
for extension in ext_list:
if f.endswith(extension) == True :
#print(f)
temp_string = os.path.join(runtimepath[1],f)
print (temp_string)
output_file.write(temp_string)
output_file.write("\n")
output_file.close();
Thanks. The below served my needs:
for root, dirs, files in os.walk(runtimepath[1]):
for file in files:
for extension in ext_list:
if file.endswith(extension) == True:
print(file)
temp_string = os.path.join(runtimepath[1],file)
print (temp_string)
output_file.write(temp_string)
output_file.write("\n")
So, i wrote this to monitor a folder for new pictures and print any that are found. It works, but I am assuming there is a more robust/efficient way to tackle this problem as I want it to run for 5-6 hours at a time.
My main problem is that I don't like using "open" while loops like this....
Would anyone tackle this differently? If so, would anyone be willing to explain?
import os
import glob
import win32com.client
import time
from pywinauto.findwindows import find_window
from pywinauto.win32functions import SetForegroundWindow
printed = []
i = 10
while i < 1000000000000000:
files = glob.glob("C://Users//pictures/*.jpg")
for filename in files:
print filename
try:
if printed.index(str(filename)) >= 0:
print printed.index(filename)
print "Image found"
except ValueError:
printed.append(filename)
os.startfile(filename, "print")
shell = win32com.client.Dispatch("WScript.Shell")
time.sleep(2)
SetForegroundWindow(find_window(title='Print Pictures'))
shell.AppActivate("Print Pictures")
shell.SendKeys("{ENTER}")
i = i + 1
time.sleep(5)
link below is related post. instead of using a long while loop you can use a watcher to trigger your operation.
How to detect new or modified files
Big thanks to scope for his comment, i have added my printing lines to the example and it works well. Code posted below for anyone who wants it, commented code is in the link code posted. Now to tidy up a few other things....
import os
import win32file
import win32event
import win
import glob
import win32com.client
import time
from pywinauto.findwindows import find_window
from pywinauto.win32functions import SetForegroundWindow
def print_photo(filename):
print filename
filename = path_to_watch +"\\" + filename[0]
os.startfile(filename, "print")
shell = win32com.client.Dispatch("WScript.Shell")
time.sleep(2)
SetForegroundWindow(find_window(title='Print Pictures'))
shell.AppActivate("Print Pictures")
shell.SendKeys("{ENTER}")
path_to_watch = os.path.abspath ("C:\\Users\\Ciaran\\Desktop\\")
change_handle = win32file.FindFirstChangeNotification (
path_to_watch,
0,
win32con.FILE_NOTIFY_CHANGE_FILE_NAME
)
try:
old_path_contents = dict ([(f, None) for f in os.listdir (path_to_watch)])
while 1:
result = win32event.WaitForSingleObject (change_handle, 500)
if result == win32con.WAIT_OBJECT_0:
new_path_contents = dict ([(f, None) for f in os.listdir (path_to_watch)])
added = [f for f in new_path_contents if not f in old_path_contents]
print_photo(added)
deleted = [f for f in old_path_contents if not f in new_path_contents]
if added: print "Added: ", ", ".join (added)
if deleted: print "Deleted: ", ", ".join (deleted)
old_path_contents = new_path_contents
win32file.FindNextChangeNotification (change_handle)
finally:
win32file.FindCloseChangeNotification (change_handle)
I'm writing a script to automate the creation of a test file/folder structure - input for another script (to move only some files according to a file list). My code below works, but is there a more pythonic way to complete the same task?
import os
import shutil
os.chdir('c:/')
if not os.path.exists('c:/pythontest'):
os.mkdir('c:/pythontest')
else:
shutil.rmtree('c:/pythontest')
os.mkdir('c:\pythontest')
os.chdir('c:/pythontest')
for i in range(0,3):
os.mkdir('folder%d' % i)
fileName = 'folder%d' % i
filePath = os.path.join(os.curdir, fileName)
print filePath
os.chdir(filePath)
for j in range(0,3):
os.mkdir('folder%d_%d' % (i,j))
fileName = 'folder%d_%d' % (i,j)
filePath = os.path.join(os.curdir, fileName)
print str(filePath)
os.chdir(filePath)
for k in range(0,3):
try:
f = open('file%d_%d_%d.txt' % (i,j,k), 'w')
except IOError:
pass
os.chdir('..')
os.chdir('..')
I can only suggest several minor style improvements -- and moving everything within a function, which speeds things up. E.g:
import os
import shutil
def doit():
shutil.rmtree('c:/pythontest', ignore_errors=True)
os.mkdir('c:/pythontest')
os.chdir('c:/pythontest')
for i in range(0,3):
fileName = 'folder%d' % i
print fileName
os.mkdir(fileName)
os.chdir(fileName)
for j in range(0,3):
fileName = 'folder%d_%d' % (i,j)
print fileName
os.mkdir(fileName)
os.chdir(fileName)
for k in range(0,3):
try:
with open('file%d_%d_%d.txt' % (i,j,k), 'w'):
pass
except IOError:
pass
os.chdir('..')
os.chdir('..')
The minor but cumulative improvements include avoidance of repetition, and avoidance of redundancy (such as prepending a './' to filenames to make exactly equivalent filepaths).
I've got a small script with monitors when files are added or removed to a directory. The next step is for me to get the script to execute the files (windows batch files) once they’ve been added to the directory. I’m struggling to understand how to use a variable with subprocess call (if this is the best way this can be acheived). Could anyone help me please? Many thanks. Code looks like this so far ;
import sys
import time
import os
inputdir = 'c:\\test\\'
os.chdir(inputdir)
contents = os.listdir(inputdir)
count = len(inputdir)
dirmtime = os.stat(inputdir).st_mtime
while True:
newmtime = os.stat(inputdir).st_mtime
if newmtime != dirmtime:
dirmtime = newmtime
newcontents = os.listdir(inputdir)
added = set(newcontents).difference(contents)
if added:
print "These files added: %s" %(" ".join(added))
import subprocess
subprocess.call(%,shell=True)
removed = set(contents).difference(newcontents)
if removed:
print "These files removed: %s" %(" ".join(removed))
contents = newcontents
time.sleep(15)
This should do what you wanted, cleaned it up a little.
import sys
import time
import os
import subprocess
def monitor_execute(directory):
dir_contents = os.listdir(directory)
last_modified = os.stat(directory).st_mtime
while True:
time.sleep(15)
modified = os.stat(directory).st_mtime
if last_modified == modified:
continue
last_modified = modified
current_contents = os.listdir(directory)
new_files = set(current_contents).difference(dir_contents)
if new_files:
print 'Found new files: %s' % ' '.join(new_files)
for new_file in new_files:
subprocess.call(new_file, shell=True)
lost_files = set(dir_contents).difference(current_contents)
if lost_files:
print 'Lost these files: %s' % ' '.join(lost_files)
dir_contents = current_contents