jlm699 320 Veteran Poster

There's no straight forward way to convert the strings 'True' and 'False' to boolean True or False, so you're best bet is probably:

if test.lower() == 'true':
    test = True
elif test.lower() == 'false':
    test = False

You could shorten those conditionals even further by only taking into account the first letter:

if test.lower()[0] == 't':
    test = True
elif test.lower()[0] == 'f':
    test = False

Considering you don't specifically need to validate the second case, you could simply use else: , and going even further you could simplify the assignment into a single line like so:

test = [False, True][test.lower()[0] == 't']
jlm699 320 Veteran Poster

Using your example string, we can separate at the whitespace using split(), and then locate the index of "welcome" using index(). Finally slicing the list by the result of index() + 1 will give us "to".

Using it for finding a row of text x lines further should be a relatively similar process as long as each line is in a list; however the major difference would be iterating over the lines, and then searching each line for the desired word, then using the index of that line plus x to find the desired line in the outermost loop.

jlm699 320 Veteran Poster

Firstly, you can use glob to get a list containing the name of each directory that starts with td like such: dirs = glob.glob(td.*) You can find the documentation about glob here.

Next, you'll want to iterate over the list that glob returns by doing something along the lines of for dir in dirs: .

Finally, to remove there exists a built-in os.rmdir(dir) which will remove the directory specified. Read up on the various operating system interfaces that the os module offers here.

jlm699 320 Veteran Poster

Refer to documentation here.

The first argument contains your arguments for the process itself so it needs to be a single element (list, tuple, etc). The remainder of parameters get passed to the Popen init function. Refer here to the remainder of items you can pass using **kwargs.

jlm699 320 Veteran Poster

sys.argv provides you the string representation of cmd line params. 'True' and 'False' are both strings, and if a string has any content in it at all, the boolean representation is True. You should simply change your condition to if test.lower() == 'true': HTH

jlm699 320 Veteran Poster

I don't know if this module has been updated to support xlsx, but it provides a method to convert xls to xml: xlrd

jlm699 320 Veteran Poster

thank s for the code. I have tried this but i keep getting the following error

maxval=int(data[0])
ValueError: invalid literal for int() with base 10: '-0.0539723'

However when i use float() instead, it works. Do you understand this error.

'-0.0539723' is not a valid integer since it is not a whole number. It is a floating point number, which requires the float() conversion. int() only works on whole numbers.

jlm699 320 Veteran Poster

Maybe as a sanity check print out the contents of ffmpeg_line before calling the subprocess to make sure you've actually constructed the proper system call.

Also, the shared computer... is it a different platform? What is the purpose of that setup? I could imagine if you were running a script on a linux box with your version of PYthon that is installed on a Windows machine you'd run into many, many problems.

jlm699 320 Veteran Poster

i use pywinauto, so will be like tat... ur answer din point to my question...

Your grammar is atrocious, therefore your question makes no sense. It is unlikely that anyone will be willing or able to answer it in its current form. I suggest revising your question and asking in a clear, concise manner using proper grammar and spelling.

jlm699 320 Veteran Poster

The file Otickers.txt is not in the working directory. Try printing the output of os.listdir('.') to see what actually is in the directory, along with os.getcwd() to see which directory you're actually working in.

also, a major flaw in your code is that any exception caught within your try block will give you the output that opening tfile failed. You should only except the relevant code, which would be the open call. So change your code to look like this:

import urllib, datetime, sys
from optparse import OptionParser

if __name__ == '__main__':
    
    parser = OptionParser()
    parser.add_option("-f", "--file", dest="tfile", action="store", default = "t.txt",
                      help="read list from file")     
    (options, args) = parser.parse_args()
    tfile = options.tfile
        
    try:
        file = open(tfile, 'r')
    except:        
        parser.error("t file %s not found" % (tfile,))
        raise SystemExit

    t = file.readlines()
    for i in range(len(t)):
        if t[i].rstrip('\n') == "TUE":
            f = "tues"
            d = "2"
            print "f:", f
                
        if t[i].rstrip('\n') == "MON":
            f = "mon,"
            d = "1"
            print "f:", f

        file.close()                

        data = urllib.urlopen(url)

        for l in data:
            if l.find(f) != -1:                    
                r = l.split(',')
                x = 2
                while x < 4:                        
                    <<do something>>
                    x = x + 1
                 print "**********************************************************************************************************************"

Also, pretty sure <<do something>> isn't valid syntax :P

Oh, and you should avoid using file as an object name since file is a reserved word in Python.

jlm699 320 Veteran Poster

That will work as well. But close file then reopen it with the create upon open or you will merely be overwriting the existing file and have debris from the previous file at the end!

What wildgoose is trying to say here is make sure you open your new file in 'write mode' instead of trying to write with your 'read mode' file handler or another 'append mode' handler.

See, when you open a file using f = open(my_file, 'w') it will either create a new file, or clear the contents of an existing file with the same name (as defined by my_file ).

jlm699 320 Veteran Poster

Define "memory error". How about pasting your traceback.

jlm699 320 Veteran Poster

You don't really need to be using regular expressions on something this simple though...

Yeah but it sounds like it's some type of built-in function to a larger utility that he used to run in perl. There's certainly better ways to build it, but he said it was URGENT so it must be life-or-death.

As they say, crises precipitate change....

jlm699 320 Veteran Poster
$str = HelloWorld;
$str =~ s/[A-Z]/_$&/g;
$str =~ s/^_//;
$str = uc($str);
print "$str";

This one's a little closer to your perl method:

import re
text = re.sub(r'([A-Z]+)',lambda x:'_'+x.group(0).lower(),'HelloPythonWorld')
text = re.sub(r'^_', r'', text)
print text.upper()
jlm699 320 Veteran Poster

what editor do you use?
Get ulipad
http://code.google.com/p/ulipad/

How long have you known about this?
And why haven't you told us until now?!

jlm699 320 Veteran Poster

jlm: You're using a little more than just sum() in that. Why didn't you at least name what the [] is? ( I never use it, and I don't have a reference handy... )

That was a list comprehension, which produces a list. Instead of using his entire for loop I cut it down into a single-line list comprehension. These are a great thing to learn when you're looking to simplify for loops.

Here's a for loop that we'll shorten:

>>> items = ['a','1','b','2','c','d','3','e']
>>> new_items = []
>>> for item in items:
...     if not item.isdigit():
...         new_items.append( 'Modified: %s' % item )
...     
>>> new_items
['Modified: a', 'Modified: b', 'Modified: c', 'Modified: d', 'Modified: e']
>>>

Now with the list comprehension:

>>> items = ['a','1','b','2','c','d','3','e']
>>> new_items = ['Modified: %s' % item for item in items if not item.isdigit()]
>>> new_items
['Modified: a', 'Modified: b', 'Modified: c', 'Modified: d', 'Modified: e']
>>>

Hopefully that's clear enough that you can follow the basic idea. If you don't understand I can try to break it down and explain each step

jlm699 320 Veteran Poster

Use sum

def test():
    number = input("Number: ")
    return sum([count*20 for count in range(1, number+1)])
jlm699 320 Veteran Poster

What is your question exactly?

Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'Rash\xf4mon'
Rashômon
>>>
jlm699 320 Veteran Poster

I think you'll probably need to make use of eval in this case:

>>> myLengths = [3, 8, 5]
>>> for eachLength in myLengths:
...     print eval("'%0" + str(eachLength) + "d' % 2")
...     
002
00000002
00002
>>>

Unless you're willing to split your above code into two steps like this:

>>> my_str = "%0" + str(myLength) + "d"
>>> my_str % 2
'002'
>>>

What's happening now is it's trying to evaluate "d" % 2 . You need to make sure the string formatting and concatenation happens before trying to use the "outer" format. If that makes sense

daviddoria commented: Perfect, quick answer! +3
jlm699 320 Veteran Poster

Running a script via python my_python.py cmd1 cmd2 cmd3 on the command line would produce the following argv structure:

import sys

print sys.argv

# Output:
# ['my_python.py', 'cmd1', 'cmd2', 'cmd3']

HTH

jlm699 320 Veteran Poster

Hi, me again, sorry if this sounds completely noobish but I have no idea what to do, even with shadwickman's help could anyone help?

You have no idea what to do with regards to what? You don't know how to download the files? Browse the source tree? What?

jlm699 320 Veteran Poster
def recordcomment(post):
    f=open('C:/commentlog.txt', 'a')
    f.write(post)
    f.write("\n")
    f.close()

It seems to me that you're trying to use the file.write() method in the same manner as print . correct me if I'm wrong, but you want a blank line (new line character \n ) in between each comment in the comments file?

If so you'll simply need an additional newline character on your write statement. It'd probably be easier if you just did a single write statement though, like this: f.write( '%s\n\n' % post ) . This statement inserts the contents of post into a string followed by two new-line characters.

Hopefully that's what you're looking for, if not try asking your question in a cohesive and clear manner.

One more thing. Are you using a=a[1:] to remove the new line character from the end of your data? This is a risky move, and probably not the best method. You'd be better off using a.strip() or a.rstrip() to take off any whitespace from the beginning and end, or simply the end (respectively) of your string. This way, if there is no newline character, you don't remove the last character of the message.

jlm699 320 Veteran Poster

No, you're not using global variables correctly. Here's the correct way to use a global variable:

# This is the global scope
my_var = 'Hi'

def my_function( input ):
    # This is inside the function's scope
    global my_var
    # This pulls my_var into the scope of the function

With that being said, using globals is not a good idea. You should restructure your code so that you don't need globals.

Here's a rewrite of your first function:

def solve(n):
    results = []
    for i in range(n,0,-1):
        if n == i:
            results.append([i])
        else:                    
            temp = [i]
            loop(n, i,temp)

    return results

There's no need to use a "global" results list since you're only making use of it within that function. Here's some info on recursive functions.

jlm699 320 Veteran Poster

Any more ideas on how I can shorten it?

How about using slicing:

site_list=
['C', ':', '\\', 'D', 'o', 'c', 'u', 'm', 'e', 'n', 't', 's', ' ', 'a', 'n', 'd', ' ', 'S', 'e', 't', 't', 'i', 'n', 'g', 's', '\\', 'S', 'r', 'a', 'v', 'a', 'n', '\\', 'M', 'y', ' ', 'D', 'o', 'c', 'u', 'm', 'e', 'n', 't', 's', '\\', 'M', 'y', ' ', 'M', 'u', 's', 'i', 'c', '\\', 'T', 'a', 'p', 'h', 'a', ' ', 'N', 'i', 'a', 'n', 'g', '.', 'm', 'p', '3']

def check_dot(my_list):
    return ''.join(my_list[-3:])

print check_dot(site_list)
jlm699 320 Veteran Poster

When you iterate over your file_list you could ignore the directories yourself like so:

file_list = glob.glob('*')
for file in file_list:
    if not os.path.isdir(file):
        # Do my stuff now on only files

EDIT:
You could also just go through and strip out the directories with a list comprehension:

file_list = [ file for file in glob.glob('*') if not os.path.isdir(file) ]
jlm699 320 Veteran Poster

i am running the worldloader.py file

Try os.getcwd() at the beginning of your script to make sure you're actually in the TPP/engine directory.

Unless you're actually running the script from within the TPP/engine directory you'll need to add it to your path. You can do that at the beginning of your script like so:

import sys

sys.path.append('/home/TPP/engine')
# Rest of your code....
vegaseat commented: thanks for a good solution +12
jlm699 320 Veteran Poster

First of all, you don't have to do int(input()) because input() returns a number anyway.

And you should start with better explaining the rest of the problem

I think he's using python 3... That being said, we don't give homework help to those that don't show effort.

Also, to the OP please use code tags when posting code on this forum. IT makes it easier to answer your questions.

jlm699 320 Veteran Poster

Where are you running your script from? Try os.getcwd() at the beginning of your script to make sure you're actually in the TPP/engine directory.

jlm699 320 Veteran Poster
shadwickman commented: Didn't know about Dive Into Python, I learned something new too! +2
jlm699 320 Veteran Poster

Refer here for details on how to make a "Package" taking advantage of __init__.py files... should get you going

jlm699 320 Veteran Poster

Use class attributes. When you get the path from the user do something like this:

self.path = path

Then your updateNebula method can be written like this:

def UpdateNebula(self, event=None):
    if 'path' in dir( self ) and self.path:
        print self.path
jlm699 320 Veteran Poster

EDIT: Concept already demonstrated

jlm699 320 Veteran Poster

I agree with everyone else here. There should never ever be a reason to open this many files at once. Ever.

You should explain what you're actually trying to do so that we can help you come up with an intelligent solution.

jlm699 320 Veteran Poster

To the both of you:

In order to preserve indentation use code tags while posting code in this forum like so:
[code=python] # Code goes inside here

[/code]

jlm699 320 Veteran Poster

Hey jlm699, how come you called random.seed()?

Habit

scru commented: oh I see; I thought it was some requirement that I'd been missing. +6
jlm699 320 Veteran Poster

And extending the above to a two element tuple:

>>> import random
>>> random.seed()
>>> mylist = [ ( random.randint(0, 100), random.randint(0, 100) ) for k in range(10) ]
>>> print(mylist)
[(83, 10), (74, 51), (19, 83), (14, 36), (12, 32), (91, 27), (96, 64), (20, 38), (37, 78), (16, 36)]
jlm699 320 Veteran Poster

I don't have any way of testing this... but have you tried using the full qualifier path? (ie, ftp://myserver/test/dir/file.txt )

Secondly, is it possible for you to simply copy the file locally and then use os.startfile ?

jlm699 320 Veteran Poster

Which is located on the ftp site, the file or the application?

jlm699 320 Veteran Poster

Why don't you put a check at the beginning of your script to see what your cwd is. Use os.getcwd() or os.listdir('.') to verify you're actually running your script from the proper directory.

jlm699 320 Veteran Poster

So if I need EasyInstall to install EGG files, how do I install EasyInstall itself?

I believe that the thought is 2.6 would be an upgrade only for the time being (since it's unlikely anybody would start using python26 before any other version). So you would use easyinstall from an earlier build of python to install the 2.6 egg.

jlm699 320 Veteran Poster

Don't use input as a variable name. Input is a python function that is equivalent to eval(raw_input(...)) ...

This may not solve your problem but it will help to distinguish whether this is a true problem or just semantics

EDIT: Now I see it. you have to call lower(). Right now you're just checking the reference to the class instead of instantiating it. But still heed my suggestion above.

jlm699 320 Veteran Poster
for index, line in lines:
for index, line in lines:
ValueError: too many values to unpack

I have done this sort of thing before, but I have never got this error :S

That's because you probably used enumerate before. Enumerate gives you index, value pairs. As it stands you're only iterating over the values of the lines list; however you're trying to unpack each value into both index and line , which is where the error stems from.

jlm699 320 Veteran Poster

You could use regular expressions... here's an example:

>>> import re
>>> pattern = 'playername = (.*)'
>>> rc = re.compile(pattern)
>>> for line in ['playername = Johnny', 'playername = Foo Bar the Clown', 'somet
hing other than playername', 'another dud', 'playername = Chocolate Rain']:
...   rcm = rc.match(line)
...   if rcm:
...     print (rcm.group(1))
...
Johnny
Foo Bar the Clown
Chocolate Rain
>>>

Here's the documentation on the Python re module. It's apparently a "weak" representation of regular expressions, but it's always proved good enough for me to use. I suggest you become familiar with them, as they can be very powerful for searching and/or replacing text among other things...

jlm699 320 Veteran Poster

I believe that subprocess.call is used to open a file as if you had "dobule-clicked" the file's icon. If you're looking to do it "within" python you'll need to search this forum for how others have done it before you.

jlm699 320 Veteran Poster
loadWords()

This is your problem. While the function actually returns the dictionary, you're never actually "catching" with anything. You should be doing something like this:

my_results = loadWords()

Then the variable my_results will contain whatever object is passed back from the function loadWords()

SoulMazer commented: Always helps and is very thorough. +1
jlm699 320 Veteran Poster

In vb I could do CSng(Right("GBP 6.19", 4)) and job done. Not so easy in python it would appear?

Not so easy? I tend to disagree...

>>> "GBP 6.19"[-4:]
'6.19'
>>> "GBP 6.19"[:3]
'GBP'
>>> "GBP 6.19".split()[1]
'6.19'
>>>

If you want more info on the bracket method it's called slicing, and can be used for just about any built-in python object. Try searching the internets for 'python slicing' if you want more info.

jlm699 320 Veteran Poster

I just made a minor modification to your regex and got the result... however there's a strange symbol appearing instead of the 'space' or tab or whatever is actually there on the page: pattern = 'GBP.*\d{1,2}[.]\d\d' Also, if you modify the pattern as such: 'GBP.*(\d{1,2}[.]\d\d)' you can use price.groups(1) to identify only the numbers.. but I'm sure you were aware of that

jlm699 320 Veteran Poster

I also use the left() and right() functions in vba to remove any whitespaces and text characters from the resulting string, any ideas on how to do that in python most gratefully received!

Use strip() like so:

>>> padded = '             foobar          '
>>> padded1 = 'foo  '
>>> padded2 = '   foo\n'
>>> padded3 = '\tfoo\tbar\n'
>>> padded.strip()
'foobar'
>>> padded1.strip()
'foo'
>>> padded2.strip()
'foo'
>>> padded3.strip()
'foo\tbar'
>>>

As you can see it removes leading and trailing white space.

When I tried your code it grabbed the YTD trailing return...

jlm699 320 Veteran Poster

Here's one way:

open_file=open('html.html','r')
file_lines=open_file.readlines()
file = file_lines[0].strip()  # First Line
loc_file = file_lines[1].strip()  # Second Line

HTH

NOTE: Using file for a variable name is not recommended as it's a reserved word in Python... I'd use something else... maybe something that's descriptive.

jlm699 320 Veteran Poster

You need to add a '\n' new line character to each line.