473,385 Members | 1,641 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Curious issue with simple code

Hi,

I have some simple code - which works...kind of..here's the code:

Expand|Select|Wrap|Line Numbers
  1. import os
  2.  
  3. def print_tree(start_dir):
  4. for f in os.listdir(start_dir):
  5. fp = os.path.join(start_dir, f)
  6. print fp
  7. if os.path.isfile(fp): # will return false if use f here!
  8. if os.path.splitext(fp)[1] == '.html':
  9. print 'html file found!'
  10. if os.path.isdir(fp):
  11. print_tree(fp)
  12.  
  13. print os.path
  14. print_tree(r'c:\intent\docn')
  15.  
As above it all works as expected. However, on the marked line, if I
use f instead of fp then that condition returns false! Surely,
isfile(f) should return true, even if I just give a filename, rather
than the full path?

If anyway can explain this I'd be grateful,

Tony

Sep 19 '06 #1
10 1391
codefire wrote:
Hi,

I have some simple code - which works...kind of..here's the code:

Expand|Select|Wrap|Line Numbers
  1. import os
  2. def print_tree(start_dir):
  3.     for f in os.listdir(start_dir):
  4.         fp = os.path.join(start_dir, f)
  5.         print fp
  6.         if os.path.isfile(fp): # will return false if use f here!
  7.             if os.path.splitext(fp)[1] == '.html':
  8.                 print 'html file found!'
  9.         if os.path.isdir(fp):
  10.             print_tree(fp)
  11. print os.path
  12. print_tree(r'c:\intent\docn')
  13.  

As above it all works as expected. However, on the marked line, if I
use f instead of fp then that condition returns false! Surely,
isfile(f) should return true, even if I just give a filename, rather
than the full path?
Of course not, unless a file with that very name exists in the current
working directory. Otherwise, where would be the difference between a
full-path and the leaf path?

Diez
Sep 19 '06 #2
codefire wrote:
As above it all works as expected. However, on the marked line, if I
use f instead of fp then that condition returns false! Surely,
isfile(f) should return true, even if I just give a filename, rather
than the full path?
try printing both "f" and "fp", and see if you can tell the difference
between the two filenames...

</F>

Sep 19 '06 #3
codefire wrote:
As above it all works as expected. However, on the marked line, if I
use f instead of fp then that condition returns false! Surely,
isfile(f) should return true, even if I just give a filename, rather
than the full path?
Hi Tony,

Actually the file is in a different directory from the working
directory, so you need to give it the path where to find it. If you
started the script from 'c:\intent\docn' (i.e., start_dir), then just
using f would work.

Regards,
Jordan

Sep 19 '06 #4
Expand|Select|Wrap|Line Numbers
  1.         
  2.                 import os
  3. def print_tree(start_dir):
  4.     for f in os.listdir(start_dir):
  5.         fp = os.path.join(start_dir, f)
  6.         print fp
  7.         if os.path.isfile(fp): # will return false if use f here!
  8.             if os.path.splitext(fp)[1] == '.html':
  9.                 print 'html file found!'
  10.         if os.path.isdir(fp):
  11.             print_tree(fp)
  12. print os.path
  13. print_tree(r'c:\intent\docn')
  14.  
  15.  
>
As above it all works as expected. However, on the marked
line, if I use f instead of fp then that condition returns
false! Surely, isfile(f) should return true, even if I
just give a filename, rather than the full path?

If anyway can explain this I'd be grateful,
If your current working directory (CWD) is the same as
start_dir, the behaviors of using "f" and "fp" will be the
same. However, if your CWD is *not* the same, "f" is
relative to the CWD, and fp is "start_dir + f" relative to
the CWD.

Thus,
>>start_dir = 'temp'
os.path.abspath(os.path.curdir)
'/home/tim'
>>f = 'filename'
fp = os.path.join(start_dir, f)
fp
'temp/filename'
>>os.path.abspath(f)
'/home/tim/filename'
>>os.path.abspath(fp)
'/home/tim/temp/filename'
You may also want to read up on os.walk:

for root, dirs, files in os.walk(start_dir):
for f in files:
if os.path.splitext(f)[1].lower()[1:] == 'html':
print 'HTML:', os.path.join(root, f)
#else:
#print 'Not HTML:', os.path.join(root, f)

which allows you to easily do what it looks like your code
is doing.

-tkc

Sep 19 '06 #5
Ah of course, isfile(f) can only return true if it can find f! :)

I'm going to investigate those other functions too :)

Thanks a lot guys!
Tony

Sep 19 '06 #6
codefire wrote:
Ah of course, isfile(f) can only return true if it can find f! :)

I'm going to investigate those other functions too :)

Thanks a lot guys!
Tony
By the way, an easier way to deal with paths is the path.py module
(http://www.jorendorff.com/articles/python/path/). Your example could
be rewritten simply as:

from path import path
for html_file in path(start_dir).walkfiles('*.html'):
print 'html file found!'

George

Sep 19 '06 #7
Hello,

I am trying to parse some files so that if a postal code exists, but is
longer than five digits it will return me only the first five digits:
....
for insDict in insureDict:
insDict['postalcode'] = insDict.get('postalcode')[:5]
....
This works, except for when I get a blank postalcode. In which case I get
the following error.
ERR exceptions.TypeError: iteration over non-sequence

What I would like to do is to check to make sure a value exists. I just
cannot seem to find the syntax to do that. (not asking anyone to write my
code, just looking for a pointer)

Thanks
--
Randomly generated signature --
In God I Trust -- on all others I use dsniff, ettercap and lczroex
Sep 19 '06 #8
eldorado wrote:
Hello,

I am trying to parse some files so that if a postal code exists, but is
longer than five digits it will return me only the first five digits:
...
for insDict in insureDict:
insDict['postalcode'] = insDict.get('postalcode')[:5]
...
This works, except for when I get a blank postalcode. In which case I get
the following error.
ERR exceptions.TypeError: iteration over non-sequence

What I would like to do is to check to make sure a value exists. I just
cannot seem to find the syntax to do that. (not asking anyone to write my
code, just looking for a pointer)

Thanks
Hint: dict.get() takes an optional second argument.

George

PS: To make a new thread, don't hit "reply" on an existing thread and
change the subject. Just make a new thread.. duh.

Sep 19 '06 #9
George Sakkis wrote:
By the way, an easier way to deal with paths is the path.py module
(http://www.jorendorff.com/articles/python/path/). Your example could
be rewritten simply as:

from path import path
for html_file in path(start_dir).walkfiles('*.html'):
print 'html file found!'
Thanks George,

I had played with it some more and ended up with the fairly succinct:

Expand|Select|Wrap|Line Numbers
  1. import os
  2. import glob
  3.  
  4. for f in glob.glob('c:\\intent\\docn\\*\\*.html'):
  5. print f
  6.  
It works quite nicely - I'm just twiddling - first time writing Python
(but like it) :)
I've bookmarked that site too for future ref.

Thanks again,
Tony

Sep 19 '06 #10
eldorado wrote:
Hello,

I am trying to parse some files so that if a postal code exists, but is
longer than five digits it will return me only the first five digits:
...
for insDict in insureDict:
insDict['postalcode'] = insDict.get('postalcode')[:5]
...
This works, except for when I get a blank postalcode. In which case I get
(the following error.
ERR exceptions.TypeError: iteration over non-sequence
What is "blank"? Do you mean "empty" as in zero-length, or "contains
one or more spaces" as in " " or do you mean "is None"? Which
statement causes the error? Could you possibly provide the traceback?

If an insDict has no key 'postalcode', then the .get() will return
None, and that insDict will have the equivalent of:
insDict['postalcode'] = None
done to it, which may not be what you want.

However this will not of itself cause "TypeError: iteration over
non-sequence" ... either

(1) insureDict is not iterable -- BTW insureDict is a strangely chosen
name; it implies it is a dictionary, BUT insDict is quite obviously a
dict, which can't be used as a key for another dict .... what is
type(insureDict)?

or (2) you are getting this error later by trying to iterate over the
values in insDict dicts -- you think the values are all strings but one
or more contain None ... show us the traceback!!
>
What I would like to do is to check to make sure a value exists.
Such a *what* value exists *where*?

HTH,
John

Sep 20 '06 #11

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

Similar topics

3
by: Paul Mateer | last post by:
Hi, I have been running some queries against a table in a my database and have noted an odd (at least it seems odd to me) performance issue. The table has approximately 5 million rows and...
17
by: Danny J. Lesandrini | last post by:
The following code works with a standard MDB to navigate to a particluar record (with a DAO recordset, of course) but it's giving me problems in an ADP I'm working on. Dim rs As ADODB.Recordset...
40
by: Confused User | last post by:
I am curious what the origins of size_t are. I see that it is usually typedef'd to be the native integer size of a particular machine. I also see that routines like strncpy(char *t, const char *s,...
17
by: Paul King | last post by:
Hi all, I have written a very simple ASP.NET page on my website that displays the results of wedding fayres based on the Venue Name selected by the user. However, when the ASP page loads for...
5
by: Chris Botha | last post by:
I am creating a worker thread from inside an aspx page and the thread does the stuff it should do, no problem. However, I have noticed running it in the debugger that it seems as if the threads...
6
by: Dave | last post by:
I was curious in regards to Access 12; specifically more fluent report formatting. I'm an average user, but from my end, I find more and more need for cleaner reports....and do not always want...
0
by: Marc Gravell | last post by:
Save me from braining myself on this wall! Please! I have an asmx which I have recently upgraded to WSE (specifically to use MTOM); however - I am now getting addressing issues, but I didn't...
3
by: CoreyWhite | last post by:
I wrote a program that shows some incredibly curious probabilities. It is a simple game where you guess a number between 0 and 2 that the computer thinks up. What is origonal about this game is...
1
by: titch | last post by:
A curious problem I've encountered which can be seen with a simple piece of HTML: <div id="a" style="position: absolute; top:5px; left: 5px; width:100px; height:100px; border: 1px solid red;">...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.