473,568 Members | 3,014 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pulling numbers from ASCII filename not working

I searched the archives but couldn't find anyone else with this
problem. Basically I'm grabbing all ASCII files in a directory and
doing geoprocessing on them. I need to calculate a z-factor based on
the latitude of the ASCII file being worked on, which is in the
filename. If I type in the code manually it works and reads the
latitude value from the ASCII filename, but when run within ArcGIS it
crashes when it gets to int(LatString). Isnumber() returned false for
Latitude as well. Is there something different about reading values
from an ASCII filename?

import sys, os, win32com.client , string, gc

# Get a list of ASCII files in the workspace for ASCII To Raster
conversion
filenames = os.listdir(gp.w orkspace)
filenames = [filename.lower( )
for filename in filenames
if (filename[-4:].lower() == ".asc" and filename[0] != "-" )]
for filename in filenames:

# For each ASCII file, create Hillshade.
# account for latitude by computing Z units using radians
Latitude = filename[1:3]
LatString = str(Latitude)
LatInt = int(LatString)
radians = LatInt * 0.0174532925
zFactor = 1/(113200 * (cos(radians)))

Jan 24 '06 #1
12 1966
First: http://www.catb.org/~esr/faqs/smart-questions.html

You say your program 'crashes' when it gets to 'int(LatString) '. I'm
guessing (and it's entirely a guess, since you don't tell us) that you
are getting an exception like 'ValueError: invalid literal for int():
whatever'. I'm guessing again that 'LatString' doesn't contain what
you think it does at this point. Have you tried inserting a print
statement to show you just what 'LatString' contains?

Jan 24 '06 #2
At lest one of the filenames (or directories) being returned by
os.listdir doesn't have integer value where you are looking.
Remember that os.listdir returns subdirectories as well as files.
You may want to look at using glob.glob() instead and limit it
to *.asc.

Secondly,

filenames = [filename.lower( ) \
for filename in filenames \
if (filename[-4:].lower() == ".asc" and filename[0] != "-" )]

is better rewritten as (not tested):

import glob
filenames=glob. glob(os.path.jo in(gp.workspace , '*.asc'))
filenames = [f.lower() for f in filenames if not f.startswith('-')]

Larry Bates

IamIan wrote:
I searched the archives but couldn't find anyone else with this
problem. Basically I'm grabbing all ASCII files in a directory and
doing geoprocessing on them. I need to calculate a z-factor based on
the latitude of the ASCII file being worked on, which is in the
filename. If I type in the code manually it works and reads the
latitude value from the ASCII filename, but when run within ArcGIS it
crashes when it gets to int(LatString). Isnumber() returned false for
Latitude as well. Is there something different about reading values
from an ASCII filename?

import sys, os, win32com.client , string, gc

# Get a list of ASCII files in the workspace for ASCII To Raster
conversion
filenames = os.listdir(gp.w orkspace)
filenames = [filename.lower( )
for filename in filenames
if (filename[-4:].lower() == ".asc" and filename[0] != "-" )]
for filename in filenames:

# For each ASCII file, create Hillshade.
# account for latitude by computing Z units using radians
Latitude = filename[1:3]
LatString = str(Latitude)
LatInt = int(LatString)
radians = LatInt * 0.0174532925
zFactor = 1/(113200 * (cos(radians)))

Jan 24 '06 #3
The exception I get is "TypeError: Cannot add value 'int' to string." I
have looked at LatString, and it is the string representation of
latitude ('17' etc.). What's odd is that the exception is raised not
when I include LatInt = int(LatString), but when I try to print
LatInt's value or multiply it by another number.

Filenames are along the lines of "N16W110.as c" - is there another way
to get LatString into a number for multiplication purposes?

Jan 24 '06 #4
"IamIan" <ia****@gmail.c om> wrote:
The exception I get is "TypeError: Cannot add value 'int' to string."


now that you've posted the exception, can you please post the code
you're using, and the *complete* traceback.

(the stuff you posted earlier contained syntax errors, and didn't con-
tain any additions. I suggest using copy/paste, rather than typing
things from memory).

</F>

Jan 24 '06 #5
On 24 Jan 2006 10:44:32 -0800, "IamIan" <ia****@gmail.c om> wrote:
I searched the archives but couldn't find anyone else with this
problem. Basically I'm grabbing all ASCII files in a directory and
doing geoprocessing on them. I need to calculate a z-factor based on
the latitude of the ASCII file being worked on, which is in the
filename. If I type in the code manually it works and reads the
latitude value from the ASCII filename, but when run within ArcGIS it
crashes when it gets to int(LatString). Isnumber() returned false for
Latitude as well. Is there something different about reading values
from an ASCII filename? Aren't you curious as to what the value of LatString was that failed?
Don't you know how to find out?

import sys, os, win32com.client , string, gc

# Get a list of ASCII files in the workspace for ASCII To Raster
conversion
filenames = os.listdir(gp.w orkspace)
filenames = [filename.lower( )
for filename in filenames
if (filename[-4:].lower() == ".asc" and filename[0] != "-" )] indentation of the above two lines would improve readability
for filename in filenames: I would try print repr(filename) here, to see what you are dealing with
# For each ASCII file, create Hillshade.
# account for latitude by computing Z units using radians
Latitude = filename[1:3]
LatString = str(Latitude) you probably won't need a print repr(LatString) here if you see the above print LatInt = int(LatString)
radians = LatInt * 0.0174532925
zFactor = 1/(113200 * (cos(radians)))

BTW, capitalizing the first letter of python variable names is counter to usual convention.

Regards,
Bengt Richter
Jan 25 '06 #6
Thank you for the replies, I'm new to Python and appreciate your
patience. I'm using Python 2.1.

To reiterate, the ASCII files in the workspace are being read correctly
and their latitude values (coming from the filenames) are successfully
being converted to string. Even doing LatInt = int(LatString) works,
however the second I try to print LatInt's value or use it in
mathematical operations, the code chokes in ArcGIS.

My full code:

# Import system modules
import sys, os, win32com.client

# Create the geoprocessor object
gp = win32com.client .Dispatch("esri Geoprocessing.G pDispatch.1")
print gp.usage("Hills hade_sa")
print gp.usage("Raste rToOtherFormat_ conversion")
print gp.usage("Defin eProjection_man agement")

# Check license availability
gp.AddMessage ("ArcInfo license is " + str(gp.CheckPro duct("ArcInfo") ))
gp.SetProduct(" ArcInfo")
gp.CheckOutExte nsion("Spatial" )

# Set workspace
workspace = "E:\\GISTes t"
gp.workspace = workspace
gp.AddMessage(" Workspace = " + gp.workspace)

filenames = os.listdir(gp.w orkspace)
filenames = [filename.lower( )
for filename in filenames
if (filename[-4:].lower() == ".asc" and filename[0] != "-" )]
for filename in filenames:

# For each ASCII file, create Hillshade.
# account for latitude by computing Z units using radians
Latitude = filename[1:3]
LatString = str(Latitude)
LatInt = int(LatString)
gp.AddMessage(" LatInt is " + LatInt)
radians = LatInt * 0.0174532925
zFactor = 1/(113200 * (cos(radians)))

The complete traceback:

Traceback (most recent call last):
File "e:\python21\py thonwin\pywin\f ramework\script utils.py", line
310, in RunScript
exec codeObject in __main__.__dict __
File "E:\Documen ts and
Settings\Admini strator\Desktop \Ian\GIS\Python \zOnly.py", line 32, in ?
gp.AddMessage(" LatInt is " + LatInt)
TypeError: cannot add type "int" to string
I tried print repr(filename) and it returned the actual filename:
'n16w099.asc' , 'n17w062.asc' , etc.

Jan 25 '06 #7
On Wed, 25 Jan 2006 12:42:20 -0800, IamIan wrote:
Thank you for the replies, I'm new to Python and appreciate your
patience. I'm using Python 2.1.

To reiterate, the ASCII files in the workspace are being read correctly
and their latitude values (coming from the filenames) are successfully
being converted to string. Even doing LatInt = int(LatString) works,
however the second I try to print LatInt's value or use it in
mathematical operations, the code chokes in ArcGIS.
[snip]
LatString = str(Latitude)
LatInt = int(LatString)
gp.AddMessage(" LatInt is " + LatInt)
Dude. You're trying to add a string to an int. What did you think would
happen?
The complete traceback:

Traceback (most recent call last):
File "e:\python21\py thonwin\pywin\f ramework\script utils.py", line
310, in RunScript
exec codeObject in __main__.__dict __
File "E:\Documen ts and
Settings\Admini strator\Desktop \Ian\GIS\Python \zOnly.py", line 32, in ?
gp.AddMessage(" LatInt is " + LatInt)
TypeError: cannot add type "int" to string


The traceback tells you exactly what is wrong, and where it is going
wrong: you are trying to add a string to an int.

What you probably want is either gp.AddMessage(" LatInt is " + LatString)
or gp.AddMessage(" LatInt is %d" % LatInt).
--
Steven.

Jan 25 '06 #8
>Dude. You're trying to add a string to an int. What did you think would
happen?


Dude. I thought it would concatenate the value for LatInt with the rest
of the sentence; I wasn't literally trying to add them. Apparently you
can only concatenate strings like this in Python.

Jan 26 '06 #9
On Wed, 25 Jan 2006 16:57:47 -0800, IamIan wrote:
Dude. You're trying to add a string to an int. What did you think would
happen?


Dude. I thought it would concatenate the value for LatInt with the rest
of the sentence; I wasn't literally trying to add them. Apparently you
can only concatenate strings like this in Python.


No. An interactive session is your friend. You can concatenate all sorts
of things, not just strings:
[2, 3, 4] + [5] [2, 3, 4, 5] (2, 3, 4,) + (5,)

(2, 3, 4, 5)

What should 4 + "5" give you? 9 or "45"?

Your description of the problem was *utterly* wrong. You said you get an
error when you try to print LatInt; but that's not true, is it? print
LatInt works fine, I bet. If you had actually posted the traceback, rather
than trying to describe it in your own words, your problem would have been
solved after one post. In other words, you sent us all on a wild goose
chase.

But the main thing is, the traceback was telling you exactly what was
wrong. Listen to it, it knows.

--
Steven.

Jan 26 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
3186
by: Hans | last post by:
Hi! I have a classic ASP site (not ASP.NET) where the user is able to download documents. The documents are stored inside an Oracle database set up for UTF-8 encoding. In the VB6 code (COM+) that fetches the document I have code like this (in my asp page I have set codepage=65001 which is utf-8) GetObjectContext("Response").AddHeader...
2
3516
by: Parintas Themis STE Kardias | last post by:
I have a field with numbers and characters how can i take only the numbers Thanks
0
1414
by: Costas Andriotis | last post by:
This is rather a IE-specific problem, but maybe someone has a solution. The HTTP headers are correct (Gecko for example understands and downloads/saves the file correctly) but IE does the wrong thing depending on the code: sf = "Non-ASCII but valid filename.extension" Response.AppendHeader("Content-Disposition", "attachment; filename=""" & sf...
2
2352
by: dotnetchic | last post by:
I'm trying to parse a binary file to help me with some analysis...what I'd like to do is take a byte of data and display its ascii char value (37='%', 38='&', etc.). private void ParseFile(string fileName) { byte data; if (File.Exists(fileName)) {
1
432
by: peter_k | last post by:
Hi, I've to implement fast library for big numbers arithmetics. I'll store the number in the table of unsigned long variables. And now i've a question: what will be faster: a) storing in one cell of the table values from 0 to 999999999 so for example number 1111222233334444 will look in table: // <- i'm reversing the cell's order +...
3
3021
by: rugger81 | last post by:
I am currently working in the sql server 2000 environment and I want to write a function to pull all dates within a given date range. I have created several diferent ways to do this but I am unsatisfied with them. Here is what I have so far: declare @Sdate as datetime declare @Edate as datetime set @SDate = '07/01/2006' set @EDate =...
12
9105
by: bg_ie | last post by:
Hi, I'm updating my program to Python 2.5, but I keep running into encoding problems. I have no ecodings defined at the start of any of my scripts. What I'd like to do is scan a directory and list all the files in it that contain a non ascii character. How would I go about doing this? Thanks,
2
3863
by: tedpottel | last post by:
Hi, My program has the following code to transfer a binary file f = open(pathanme+filename,'rb') print "start transfer" self.fthHandle.storbinary('STOR '+filename, f) How can I do an ASCII file transfer?????? -Ted
9
10010
by: Aamir Mahmood | last post by:
Hi, I have working on a system in which I have to manipulate *very* big numbers. Like 32368060745625089670148189374568111100874165870871388541651800834565616109380834613212956588769877 They may be upto 10000 digits long. These numbers are coming through a device in ascii format, I am creating a text file and saving these numbers in the...
0
7693
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8118
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7962
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6277
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5501
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3651
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3631
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2105
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
933
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.