Issues with python path - python

I am working on a program in Arcgis however, I have a python issue.
While trying to run the following script I am getting an invalid MXD error which seems to suggest that it cannot find the location of my MXD file.
# modified by ESRI for use as a toolbox script tool
## imported sys to get the raw inputs and os to use for path separator
import arcpy, sys, os
# Set OverWrite if files already exist
arcpy.OverWriteOutput = 1
print "Enter folder path:"
mapDoc = raw_input()
#mapDoc = sys.argv[1]
print os.path.dirname(mapDoc)
# set a variable to the full path and file name of the MXD
fullnam = os.path.basename(mapDoc)
# Strip off the MXD file extension and store as string variable for use in the 'out_pdf'
nam = fullnam.strip(".mxd")
print nam
# Commented this out, since it doesnt need to be a parameter when you use the MXD name as the PDF name
##print "Enter save as name:"
##mapName = sys.argv[2]
map = arcpy.mapping
mxd = map.MapDocument(mapDoc)
map_document = mxd
#out_pdf = r"K:\projects" + "\\" + mapName + ".pdf"
#out_pdf = r"K:\projects" + os.sep + mapName + ".pdf"
#out_pdf = os.path.dirname(mapDoc) + os.sep + mapName + ".pdf"
out_pdf = os.path.dirname(mapDoc) + os.sep + nam + ".pdf"
# Set all the parameters as variables here:
data_frame = 'PAGE_LAYOUT'
resolution = "300"
image_quality = "NORMAL"
colorspace = "RGB"
compress_vectors = "True"
image_compression = "DEFLATE"
picture_symbol = 'RASTERIZE_BITMAP'
convert_markers = "False"
embed_fonts = "True"
layers_attributes = "NONE"
georef_info = "False"
# Due to a known issue, the df_export_width and df_export_height must be set to integers in the code:
map.ExportToPDF(map_document, out_pdf, data_frame, 640, 480, resolution, image_quality, colorspace, compress_vectors, image_compression, picture_symbol, convert_markers, embed_fonts, layers_attributes, georef_info)
# This gives feedback in the script tool dialog:
arcpy.GetMessages()
Now please look at the command prompt.
(arcgispro-py3) C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3>"C:\Us
ers\ant\Documents\MyCensus_Files\Python script\Export2PDF.py"
Enter folder path:
C:\Users\ant\Documents\MyCensus_Files\Python script
C:\Users\ant\Documents\MyCensus_Files
Python script
Traceback (most recent call last):
File "C:\Users\ant\Documents\MyCensus_Files\Python script\Export2PDF.py
", line 22, in <module>
mxd = map.MapDocument(mapDoc)
File "C:\Program Files (x86)\ArcGIS\Desktop10.6\ArcPy\arcpy\arcobjects\mixins.
py", line 651, in __init__
assert (os.path.isfile(mxd) or (mxd.lower() == "current")), gp.getIDMessage(
89004, "Invalid MXD filename")
AssertionError: Invalid MXD filename.
As you can see, the path I enter is different from what is being returned by print and I think that is what's causing my issue. Would appreciate it anyone could assist fixing handling this path error or with a python script that accomplishes converting MXD to PDF.
Regards

If you print out mapDoc right before the line map.MapDocument(mapDoc), you would see that you're trying to pass C:\Users\ant\Documents\MyCensus_Files\Python script as a mxd file. That's a directory, not a mxd file.

Try this:
import arcpy, sys, os
arcpy.OverWriteOutput = 1
mapDoc = os.path.join("C:/", "Users", "ant", "Documents", "MyCensus_Files", "Python_script", "test.mxd")
map = arcpy.mapping
mxd = map.MapDocument(mapDoc)
# ...

Related

how to import more than 1 in python

i am trying to import a file containing an image in python but i am getting an error writing the directory name while importing.
this is my directory:
my code is :
path = 'file_dir/dir_pict'
rd = []
label[]
Size = 32
for folder in os.listdir(path):
for file in os.listdir(os.path.join(path, folder)):
if file.endswith("png"):
label.append(folder)
pict = cv.imread(os.path.join(path, folder, file))
imgRGB = cv.cvtColor(pict, cv.COLORBGR2RGB)
there is an error: The system cannot find the path specified
maybe the file I entered was wrong name : path = 'file_dir/dir_pict'
i've try : path = 'r"C:\Users\riandra putra\OneDrive\Documents\file_dir"
but get an error :
NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\\Users\\riandra putra\\OneDrive\\Documents\\file_dir\\program01.py'
i need your opinion about this
IIUC
path = 'dir_pict'
rd = []
label = []
Size = 32
for folder in os.listdir(path):
for file in os.listdir(path):
if file.endswith("png"):
label.append(folder)
pict = cv.imread(os.path.join(path, file))
imgRGB = cv.cvtColor(pict, cv.COLORBGR2RGB)
This should do what you want.
The path is correct. However, to make it works smoothly, you should add a 'r' before the path itself as per the following.
path = r'file_dir/dir_pict'
rd = []
label = []
Size = 32
for folder in os.listdir(path):
for file in os.listdir(os.path.join(path, folder)):
if file.endswith("png"):
label.append(folder)
pict = cv.imread(os.path.join(path, folder, file))
imgRGB = cv.cvtColor(pict, cv.COLORBGR2RGB)
In this way, it should work as expected. I noticed that you also missed the "=" while defining the label array, but it happens :D
For more info, look the docs https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals

How do I get every file of an extension from a directory to another? I wrote a code but I'm getting an exception

This piece of code is my first attempt at creating a program. I'm getting an error when running it that reads:
PermissionError: [WinError 32] The process cannot access the file
because it is being used by another process:
'C:\Users\gabri\Desktop\' -> 'C:\Users\gabri\Desktop\Planilhas
Excel\'
What am I doing wrong? The goal of this program is to get all excel, then pdf, then word files and put them in folders created by the program.
import os
from glob import glob
# import cx_Freeze
print("Digite o diretório de origem.")
dirOrigem = input()
os.chdir(dirOrigem)
excel_files = glob('*.xlsx')
excel_files.append(''.join(glob('*.xls')))
dirDestinoXL = dirOrigem + '\\' + 'Planilhas Excel'
if not os.path.exists(dirDestinoXL):
os.makedirs(dirDestinoXL)
for i in excel_files:
os.rename(f'{dirOrigem}\\{"".join(i)}', f'{dirDestinoXL}\\{"".join(i)}')
os.chdir(dirOrigem)
pdf_files = glob('*.pdf')
dirDestinoPDF = dirOrigem + '\\' + 'PDF'
if not os.path.exists(dirDestinoPDF):
os.makedirs(dirDestinoPDF)
for p in pdf_files:
os.rename(f'{dirOrigem}\\{"".join(p)}', f'{dirDestinoPDF}\\{"".join(p)}')
os.chdir(dirOrigem)
word_files = glob('*.doc')
word_files.append(glob('*.docx'))
dirDestinoWord = dirOrigem + '\\' + 'Word'
if not os.path.exists(dirDestinoWord):
os.makedirs(dirDestinoWord)
for d in word_files:
os.rename(f'{dirOrigem}\\{"".join(d)}', f'{dirDestinoWord}\\{"".join(d)}')
I tried your program and it doesn't work as it is on my computer. I changed some lines and it works. Hope it helps
import os
from glob import glob
dirOrigem = r'C:\Users\fchal\Desktop\temp' # here I changed the code just because I didn't want to bother using input()
os.chdir(dirOrigem)
excel_files = glob('*.xlsx')
excel_files.extend(glob('*.xls'))
dirDestinoXL = dirOrigem + '\\' + 'xlsfile'
if not os.path.exists(dirDestinoXL):
os.makedirs(dirDestinoXL)
for i in excel_files:
os.rename(i, os.path.join(dirDestinoXL, i))
# same procedure for pdf and word files
I know that glob can be a mess sometimes. And if the files are open, you can get errors. Here's what I would do:
import os
def move_files_with_extension(from_dir, to_dir, *extensions):
if not os.path.isdir(from_dir):
raise ValueError('{} is not a real directory'.format(from_dir))
elif not os.path.isdir(to_dir):
raise ValueError('{} is not a real directory'.format(to_dir))
files_with_extensions = all_files_with_extensions_in(from_dir, *extensions)
for file_path in files_with_extensions:
os.rename(file_path, os.path.join(to_dir, os.path.basename(file_path)))
def all_files_with_extensions_in(dir, *extensions):
files_with_extensions = list()
for dir_path, dir_names, file_names in os.walk(dir):
for file_name in file_names:
if file_name.endswith(extensions):
files_with_extensions.append(os.path.join(dir_path, file_name))
return files_with_extensions
and then you can do:
dirOrigem = input()
excel_location = os.path.join(dirOrigem, 'Planilhas Excel')
move_files_with_extension(dirOrigem, excel_location, '.xls', '.xlsx')
and so on

Python Win32Com - ExportAsFixedFormat - MS Excel 2010 file

I have spent the day trying to figure out how to export out a MS Excel File as a PDF. I am in desperate need of someone smarter than I:
Here is what I have so far and the error I get:
import os
import win32com.client
import win32com.client.dynamic
import datetime
import time
#
#Path to Read from where you want all the files read from
InputWkbkPath = "O:/MIS/Reporting/Field Reports/2014_Template_Files/w_code/"
obj = win32com.client.Dispatch("Outlook.Application")
xlApp = win32com.client.DispatchEx('Excel.Application')
OutputWkbkPath ='O:/MIS/Reporting/Field Reports/2015_Template_Files/Directors /Templates/20150123_Archive/'
for subdir, dirs, files in os.walk(InputWkbkPath):
for file in files:
#print os.path.join(subdir, file)
ip= os.path.join(subdir, file)
xlwb= xlApp.Workbooks.Open(ip)
#print xlwb
currentyear = datetime.date.today().strftime("%Y")
currentmonth = datetime.date.today().strftime("%B")
currentday = datetime.date.today().strftime("%d")
currentdate = currentmonth+"-"+currentday+"-"+currentyear
participant = xlwb.Worksheets(1).Range("C4").Value
title = xlwb.Worksheets(1).Range("C5").Value
StaffCode = xlwb.Worksheets(1).Range("C6").Value
OfficeName = xlwb.Worksheets(1).Range("C7").Value
LOCode = xlwb.Worksheets(1).Range("C8").Value
Region = xlwb.Worksheets(1).Range("C9").Value
ESN = str(xlwb.Worksheets(1).Range("C10").Value)
ParticipantEmail= xlwb.Worksheets(1).Range("C11").Value
MDEmail= xlwb.Worksheets(1).Range("C12").Value
RVPEmail = xlwb.Worksheets(1).Range("C13").Value
if title == "Director" or title == "DIRECTOR":
FileName = LOCode+"_"+participant+"_"+ESN+"_Comp_Model_"+currentdate+".xlsx"
#print FileName
else:
FileName = Region+"_"+LOCode+"_"+participant+"_"+ESN+"_Comp_Model_"+currentdate+".pdf"
OutputFile=OutputWkbkPath+FileName
xlwb.Worksheets(1).Activate
#print OutputFile
ws=xlwb.Worksheets(1)
ws.Visible = 1
xlwb.ExportAsFixedFormat(Type="xlTypePDF",OutputFile)
xlwb.Close(True)
I get the following error:
C:\Python27\python.exe C:/Users/username/PycharmProjects/File_Names/Loop_Throug_Open.py
File "C:/Users/username/PycharmProjects/File_Names/Loop_Throug_Open.py", line 55
xlwb.ExportAsFixedFormat(Type="xlTypePDF",OutputFile)
SyntaxError: non-keyword arg after keyword arg
Process finished with exit code 1
Please help. I can not find any on it in the groups.
Thank you ahead of time.
Robert
The problem was in the ExportAsFixedFormat method:
I changed to the following:
xlwb.ExportAsFixedFormat(0, OutputFile)
I also had to put the path with double regular slashes. So the outputWkbkPath looks like the following:
OutputWkbkPath ='O:\\MIS/Reporting\\Field Bonus Plan Reports\\2015__Files\\ DirectorsTemplates\\20150123_Archive\\'
I hope this helps someone else. The following post actually got me there:
.xlsx and xls(Latest Versions) to pdf using python
It is not the same package/module but that part works.

trying to store a file in a string python

This is one of my first python projects, and i'm trying to make a script that would write a script which can re-create the src/ directory. this would be what i distribute to users. It uses walk, and writes a python file that first creates all the directories, and then writes the files. The issue i have is making the the files into a single string that i can write to a file.
This is the program i have:
import os
import pickle
src = os.path.dirname(os.path.realpath(__file__)) + os.sep + 'src'
fPack = 'import os \nimport pickle \nmyDir = os.path.dirname(os.path.realpath(__file__))'
Pack =''
print 'Packing ' + src
pickle
for root, dirs, files in os.walk(src, topdown=True):
for name in files:
print os.path.join(root, name)
f = open(os.path.join(root, name), 'r')
Pack = Pack + '\nf = open(os.path.join(myDir,\'' + name + '\'), \'w\')'
fileCont = pickle.dumps(f.read())
Pack = Pack + '\nf.write(pickle.loads(\'' + fileCont + '\'))'
for name in dirs:
print os.path.join(root, name)
fPack = fPack + '\nos.makedirs(os.path.join(myDir,\'' + name + '\'))'
print '==================================================\n\n\n'
print fPack + Pack
f = open(os.getcwd() + os.sep + 'dist' + os.sep + 'Pack.py', 'w')
f.write(fPack)
f.write(Pack)
And if i run it in a directory with on subdirectory, and on file inside it creates this file
import os
import pickle
myDir = os.path.dirname(os.path.realpath(__file__))
os.makedirs(os.path.join(myDir,'SphereText'))
f = open(os.path.join(myDir,'TextMain.py'), 'w')
f.write(pickle.loads('S"########################################################\n#Main SphereText file. #\n#SpereText is a simple Notepad-Like plain text editor #\n########################################################\n\nfrom Tkinter import *\nfrom tkFileDialog import *\nimport tkSimpleDialog\n\nroot = Tk()\nroot.title('SphereText')\n\ndef fSave():\n fileName = asksaveasfilename(parent=root)\n f = open(fileName, 'w')\n f.write(text.get(1.0,END))\n\ndef fOpen():\n fileName = ''\n fileName = askopenfilename(parent=root)\n f = open(fileName, 'r')\n text.delete(1.0,END)\n text.insert(1.0, f.read())\n\ndef tReplace():\n Old = tkSimpleDialog.askstring('SphereText', 'Replace:')\n print Old\n New = tkSimpleDialog.askstring('SphereText', 'With:')\n print New\n content = text.get(1.0,END)\n content = content.replace(Old, New)\n text.delete(1.0,END)\n text.insert(1.0, content)\n \nmenubar = Menu(root)\nmenubar.add_command(label='Save', command=fSave)\nmenubar.add_command(label='Open', command=fOpen)\nmenubar.add_command(label='Replace', command=tReplace)\nroot.config(menu=menubar)\n\ntext = Text(root, wrap=WORD)\n\ntext.pack()\n\nroot.mainloop()\n"
p0
.'))
The 's aren't escaped, and there are two line breaks at the end. i thought that the whole point of serializing was that you could always read it back the same way. Anyone know how i can mak the file a valid string?
Sorry about the newbish question, i just found out i had been trying to reinvent the wheel. apparently, that already exists under the name Squeeze.

python os.rename(...) won't work !

I am writing a Python function to change the extension of a list of files into another extension, like txt into rar, that's just an idle example. But I'm getting an error. The code is:
import os
def dTask():
#Get a file name list
file_list = os.listdir('C:\Users\B\Desktop\sil\sil2')
#Change the extensions
for file_name in file_list:
entry_pos = 0;
#Filter the file name first for '.'
for position in range(0, len(file_name)):
if file_name[position] == '.':
break
new_file_name = file_name[0:position]
#Filtering done !
#Using the name filtered, add extension to that name
new_file_name = new_file_name + '.rar'
#rename the entry in the file list, using new file name
print 'Expected change from: ', file_list[entry_pos]
print 'into File name: ', new_file_name
os.rename(file_list[entry_pos], new_file_name)
++entry_pos
Error:
>>> dTask()
Expected change from: New Text Document (2).txt
into File name: New Text Document (2).rar
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
dTask()
File "C:\Users\B\Desktop\dTask.py", line 19, in dTask
os.rename(file_list[entry_pos], new_file_name)
WindowsError: [Error 2] The system cannot find the file specified
I can succeed in getting the file name with another extension in variable level as you can see in the print-out, but not in reality because I can not end this process in OS level. The error is coming from os.rename(...). Any idea how to fix this ?
As the others have already stated, you either need to provide the path to those files or switch the current working directory so the os can find the files.
++entry_pos doesn't do anything. There is no increment operator in Python. Prefix + is just there fore symmetry with prefix -. Prefixing something with two + is just two no-ops. So you're not actually doing anything (and after you change it to entry_pos += 1, you're still resetting it to zero in each iteration.
Also, your code is very inelegant - for example, you are using a separate index to file_list and fail to keep that in synch with the iteration variable file_name, even though you could just use that one! To show how this can be done better.
-
def rename_by_ext(to_ext, path):
if to_ext[0] != '.':
to_ext = '.'+to_ext
print "Renaming files in", path
for file_name in os.listdir(path):
root, ext = os.path.splitext(file_name)
print "Renaming", file_name, "to", root+ext
os.rename(os.path.join(path, file_name), os.path.join(path, root+to_ext))
rename_by_ext('.rar', '...')
os.rename really doesn't like variables. Use shutil. Example taken from How to copy and move files with Shutil.
import shutil
import os
source = os.listdir("/tmp/")
destination = "/tmp/newfolder/"
for files in source:
if files.endswith(".txt"):
shutil.move(files,destination)
In your case:
import shutil
shutil.move(file_list[entry_pos], new_file_name)
You also want to double backslashes to escape them in Python strings, so instead of
file_list = os.listdir('C:\Users\B\Desktop\sil\sil2')
you want
file_list = os.listdir('C:\\Users\\B\\Desktop\\sil\\sil2')
Or use forward slashes - Python magically treats them as path separators on Windows.
You must use the full path for the rename.
import os
def dTask():
#Get a file name list
dir = 'C:\Users\B\Desktop\sil\sil2'
file_list = os.listdir(dir)
#Change the extensions
for file_name in file_list:
entry_pos = 0;
#Filter the file name first for '.'
for position in range(0, len(file_name)):
if file_name[position] == '.':
break
new_file_name = file_name[0:position]
#Filtering done !
#Using the name filtered, add extension to that name
new_file_name = new_file_name + '.rar'
#rename the entry in the file list, using new file name
print 'Expected change from: ', file_list[entry_pos]
print 'into File name: ', new_file_name
os.rename( os.path.join(dir, file_list[entry_pos]), os.path.join(dir,new_file_name))
++entry_pos
If you aren't in the directory C:\Users\B\Desktop\sil\sil2, then Python certainly won't be able to find those files.
import os
def extChange(path,newExt,oldExt=""):
if path.endswith != "\\" and path.endswith != "/":
myPath = path + "\\"
directory = os.listdir(myPath)
for i in directory:
x = myPath + i[:-4] + "." + newExt
y = myPath + i
if oldExt == "":
os.rename(y,x)
else:
if i[-4:] == "." + oldExt:
os.rename(y,x)
now call it:
extChange("C:/testfolder/","txt","lua") #this will change all .txt files in C:/testfolder to .lua files
extChange("C:/testfolder/","txt") #leaving the last parameter out will change all files in C:/testfolder to .txt

Categories

Resources