Can't Get readshapefile() to read the .shp - python

So I've recently gotten into mapmaking with Python using matplotlib and Basemap. For some reason my code breaks when I go to execute m.readshapefile() because it can't find the .shp.
I downloaded the .zip for this and put it on my desktop at C:\Users\mattd\Desktop\pop\ne_110m_populated_places. I put
m.readshapefile('C:\Users\mattd\Desktop\pop\ne_110m_populated_places',
'populated_places')
and it can't breaks because it can't find the file.

In the link you attached, there was no file named populated_places
I did find a ne_110m_populated_places.shp. Also, it's also good practice to name your variables what they are and do sanity checks in your own code instead of relying on libraries to do that for you.
from os import path
shape_dir = 'C:\Users\mattd\Desktop\pop\ne_110m_populated_places'
shape_file = 'ne_110m_populated_places'
shape_file_full = shape_file + '.shp'
# check if we provided valid paths to our file and directory
if path.isdir(shape_dir) is False:
print ("%s does not exist!" % (shape_dir))
quit()
if path.isfile(shape_file_fill) is False:
print ("%s does not exist" % (shape_file_full))
quit()
# if it makes it here then you know it's an issue with the library
base_map = Basemap(...)
base_map.readshapefile(shape_dir, shape_file)

Related

How to detect a .lock file in a geodatabase

I am very new to python, but I have written a simple python script tool for automating the process of updating mosaic datasets at my job. The tool runs great, but sometimes I get the dreaded 9999999 error, or "the geodatase already exists" when I try to overwrite the data.
The file structure is c:\users\my.name\projects\ImageryMosaic\Alachua_2014\Alachua_2014_mosaic.gdb. After some research, I determined that the lock was being placed on the FGDB whenever I opened the newly created mosaic dataset inside of the FGDB to check for errors after running the tool. I would like to be able to overwrite the data instead of having to delete it, so I am using the arcpy.env.overwriteOutput statement in my script. This works fine unless I open the dataset after running the tool. Since other people will be using this tool, I don't want them scratching thier heads for hours like me, so it would be nice if the script tool could look for the presence of a .Lock file in the geodatabase. That way I could at least provide a statement in the script as to why the tool failed in lieu of the unhelpful 9999999 error. I know about arcpy.TestSchemaLock, but I don't think that will work in this case since I am not trying to place a lock and I want to overwrite the FGDB, not edit it.
Late but this function below will check for lock files in given (gdb) path.
def lockFileExist(path = None):
if path == None:
import traceback
raise Exception("Invalid Path!")
else:
import glob
full_file_paths = glob.glob(path+"\\*.lock")
for f in full_file_paths:
if f.endswith(".lock"):
return True
return False
if lockFileExist(r"D:\sample.gdb"):
print "Lock file found in gdb. Aborting..."
else:
print "No lock files found!. Ready for processing..."

python - open wav file in default program (Linux)

I want to open .wav file in default program. But it doesn´t work. This is my code:
audiofile=(myFile[index]+".wav") # I have all files in array (without ".wav")
try:
try:
os.system('xdg-open audiofile')
except:
os.system('start audiofile')
except:
print "error"
I don´t get any error, but it doesn´t work. How can I solve it? Thank you.
You aren't substituting the name of the audio file into your OS commands, so it can't possibly work.
You'd need something like:
os.system('xdg-open ' + audiofile)
This assumes that you have a default application associated with .wav files, which of course you can test by trying your command manually.
You might also want to check the return value of os.system for an error code, rather than relying on exceptions.
First of all, you should fill the variable audiofile into the command, not the string 'audiofile' itself
os.system('xdg-open %s' % audiofile)
Second,
os.system will NOT throw an exception when xdg-open or start doesn't exist in system.
Determine the type of system first by platform.system
>>> import platform
>>> platform.system()
'Linux'

Open Image Error Python

Hello everyone I'm trying to open a image that i have downloaded through a link. I searched on the site and found something very useful and implemented that into my code.
*if* __name__ == "__main__":
import urllib
droste = urllib.urlopen("http://is.gd/cHqT")
with open("droste.png", "wb") as imgFile:
imgFile.write(droste.read())
print "Got it!"
droste = Image.open("droste.png")
while droste:
droste.show()
droste = reveal(droste)
if droste:
open("droste.png", "wb").write(droste)
droste = Image.open("droste.png")
The error occurs on the 7th line "droste = Image.open("droste.png")". I'm getting a IOError: cannot identify image file. I know the image has been downloaded because the codes runs great until that particular line and the line print "Got it!" actually confirms that its been downloaded. I don't know if I need to specify the path of the image file in the parameter in the open instead the of image name. Or maybe I need to check the path of the file. Please help.
Your code is functional. The problem is how you are running it. You mentioned in your comments that you are using PythonAnywhere. PythonAnywhere is not set up to do anything graphical. It will download the image into the correct directory, but PIL will not function correctly with PythonAnywhere.
Try the following code to test this.
import urllib
if __name__ == "__main__":
droste = urllib.urlopen("http://is.gd/cHqT")
with open("droste.png", "wb") as imgFile:
imgFile.write(droste.read())
print "Got it!"
print "Now lets test if it really exists..."
try:
with open("droste.png", "rb") as imgFile:
pass
print "There were no errors so the file exists"
except:
print "ERROR: image was not saved properly!"
If you start up a BASH session with PythonAnywhere, you will see that the file droste.png exists, and you can download it to your computer and view it. Your program is OK.
If you really want to use your program, or get serious about python programming. You really should install Python locally to your computer. If you want to keep your code in the cloud, then use dropbox, github, or bitbucket. PythonAnywhere has uses, but normally you will just want to have python on your computer.

Python: problem with tiny script to delete files

I have a project that used to be under SVN, but now I'm moving it to Mercurial, so I want to clear out all the .svn files.
It's a little too big to do it by hand, so I decided to write a python script to do it. But it isn't working.
def cleandir(dir_path):
print "Cleaning %s\n" % dir_path
toDelete = []
files = os.listdir(dir_path)
for filedir in files:
print "considering %s" % filedir
# continue
if filedir == '.' or filedir == '..':
print "skipping %s" % filedir
continue
path = dir_path + os.sep + filedir
if os.path.isdir(path):
cleandir(path)
else:
print "not dir: %s" % path
if 'svn' in filedir:
toDelete.append(path)
print "Files to be deleted:"
for candidate in toDelete:
print candidate
print "Delete all? [y|n]"
choice = raw_input()
if choice == 'y':
for filedir in toDelete:
if os.path.isdir(filedir):
os.rmdir(filedir)
else:
os.unlink(filedir)
exit()
if __name__ == "__main__":
cleandir(dir)
The print statements show that it's only "considering" the filedirs whose names start with ".". However, if I uncomment the continue statement, all the filedirs are "considered". Why is this?
Or is there some other utility that already exists to recursively de-SVN-ify a directory tree?
At the very least you should not re-invent the wheel for recursive directory traversal and just use os.walk.
This doesn't answer your Python question, but there's an easier way to do what you want: svn export will write your tree of files some place new without all the .svn directories.
The reason 'continue' shows all the folders being considered is because exit() is being called at the end of the function. The call to exit() will exit Python after the first directory is searched. If you change it to 'return' your function will be called recursively.
Also os.listdir does not return '.' or '..' so you don't need a check or any continue statements.
:-)
Davy
I have a project that used to be under SVN, but now I'm moving it to Mercurial, so I want to clear out all the .svn files.
Not to side step your question here (and I know it's been answered, correctly no less) but if you want to export your source from Mercurial, you should use the 'export' command of SVN.... You don't need to manually (or pragmatically) remove all of the .svn folders....
(This is mainly for others' that come up this post looking how to do this)
Also, there are SVN to Mercurial importers....

OS X: Determine Trash location for a given path

Simply moving the file to ~/.Trash/ will not work, as if the file os on an external drive, it will move the file to the main system drive..
Also, there are other conditions, like files on external drives get moved to /Volumes/.Trash/501/ (or whatever the current user's ID is)
Given a file or folder path, what is the correct way to determine the trash folder? I imagine the language is pretty irrelevant, but I intend to use Python
Based upon code from http://www.cocoadev.com/index.pl?MoveToTrash I have came up with the following:
def get_trash_path(input_file):
path, file = os.path.split(input_file)
if path.startswith("/Volumes/"):
# /Volumes/driveName/.Trashes/<uid>
s = path.split(os.path.sep)
# s[2] is drive name ([0] is empty, [1] is Volumes)
trash_path = os.path.join("/Volumes", s[2], ".Trashes", str(os.getuid()))
if not os.path.isdir(trash_path):
raise IOError("Volume appears to be a network drive (%s could not be found)" % (trash_path))
else:
trash_path = os.path.join(os.getenv("HOME"), ".Trash")
return trash_path
Fairly basic, and there's a few things that have to be done seperatly, particularly checking if the filename already exist in trash (to avoid overwriting) and the actual moving to trash, but it seems to cover most things (internal, external and network drives)
Update: I wanted to trash a file in a Python script, so I re-implemented Dave Dribin's solution in Python:
from AppKit import NSURL
from ScriptingBridge import SBApplication
def trashPath(path):
"""Trashes a path using the Finder, via OS X's Scripting Bridge.
"""
targetfile = NSURL.fileURLWithPath_(path)
finder = SBApplication.applicationWithBundleIdentifier_("com.apple.Finder")
items = finder.items().objectAtLocation_(targetfile)
items.delete()
Usage is simple:
trashPath("/tmp/examplefile")
Alternatively, if you're on OS X 10.5, you could use Scripting Bridge to delete files via the Finder. I've done this in Ruby code here via RubyCocoa. The the gist of it is:
url = NSURL.fileURLWithPath(path)
finder = SBApplication.applicationWithBundleIdentifier("com.apple.Finder")
item = finder.items.objectAtLocation(url)
item.delete
You could easily do something similar with PyObjC.
A better way is NSWorkspaceRecycleOperation, which is one of the operations you can use with -[NSWorkspace performFileOperation:source:destination:files:tag:]. The constant's name is another artifact of Cocoa's NeXT heritage; its function is to move the item to the Trash.
Since it's part of Cocoa, it should be available to both Python and Ruby.
In Python, without using the scripting bridge, you can do this:
from AppKit import NSWorkspace, NSWorkspaceRecycleOperation
source = "path holding files"
files = ["file1", "file2"]
ws = NSWorkspace.sharedWorkspace()
ws.performFileOperation_source_destination_files_tag_(NSWorkspaceRecycleOperation, source, "", files, None)
The File Manager API has a pair of functions called FSMoveObjectToTrashAsync and FSPathMoveObjectToTrashSync.
Not sure if that is exposed to Python or not.
Another one in ruby:
Appscript.app('Finder').items[MacTypes::Alias.path(path)].delete
You will need rb-appscript gem, you can read about it here

Categories

Resources