Re: [Tutor] Impossible Else as Exception

2013-04-10 Thread Alan Gauld

On 10/04/13 07:18, Jordan wrote:


Alan you are right, the code should be better tested, but test driven
development seems like it would take me forever to complete even small
tasks, there is so much to be tested.  I have limited time to program
with my wife and kids, but do you think test driven development is still
the way to go?


Do you want to spend your time writing tests that identify bugs 
immediately or spend your time debugging code after you've written it 
and every time you modify it?


A lot depends on how often you will be going back to the code in the 
future. If this is a use once throw away project then TDD may be 
overkill. If you are likely to want to enhance it in the future TDD

is an investment to save time.

I confess I don't use TDD all of the time and even with TDD errors will 
still sneak through. But TDD improves your chances of finding them early 
considerably.


It will usually take the same amount of total time, its just a question 
of how you use it.


HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Chapter 3 Projects

2013-04-10 Thread Alan Gauld

On 10/04/13 04:11, Dave Angel wrote:


I'd do it like this


score = raw_input('score? ')


That would need to be:
 score = int(raw_input('score? ')



Oops, yes. Good catch.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] running python from windows command prompt

2013-04-10 Thread Arijit Ukil
I like to run a python program "my_python.py" from windows command prompt. 
This program ( a function called testing) takes input as block data (say 
data = [1,2,3,4] and outputs processed single data.

import math

def avrg(data):
return sum(data)/len(data)

def testing (data):
val = avrg(data)
out = pow(val,2)
return out

Pls help.

Regards,
Arijit Ukil
Tata Consultancy Services
Mailto: arijit.u...@tcs.com
Website: http://www.tcs.com

Experience certainty.   IT Services
Business Solutions
Outsourcing

=-=-=
Notice: The information contained in this e-mail
message and/or attachments to it may contain 
confidential or privileged information. If you are 
not the intended recipient, any dissemination, use, 
review, distribution, printing or copying of the 
information contained in this e-mail message 
and/or attachments to it are strictly prohibited. If 
you have received this communication in error, 
please notify us by reply e-mail or telephone and 
immediately and permanently delete the message 
and any attachments. Thank you


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Impossible Else as Exception

2013-04-10 Thread Dave Angel

On 04/10/2013 02:18 AM, Jordan wrote:

Thank you all for the feedback and suggestions.  I have never used an
assertion, before so I will read up on the concept.



One comment about assertion.  Even though an optimized run will ignore 
the assertion itself, it can save a (small) amount of time avoiding any 
other overhead "preparing" for the assertion.  So I'd make your if/elif 
logic something like this:




if condition == 1:
do something with 1
else:   #Note, condition must be 2, unless something above is flawed
assert(condition==2, "Condition must be 1 or 2, something's wrong")
do something with 2


One more comment I didn't notice anybody else point out.  Many times, 
instead of hoping the code remains consistent, you can make it much more 
likely by changing types.  For example, instead of naming the conditions 
1 and 2, name then True and False.  Now, the test becomes:


if condition:
do something with 1
else:
do something with 2

This isn't as perfect an answer as with typed languages, because 
somebody can slip in some other type.


--
DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] running python from windows command prompt

2013-04-10 Thread Dave Angel
(Please don't hijack a thread with an unrelated question.  You're no 
doing yourself any favors, as any decent thread-viewer will hide your 
new subject line, and group the whole thread with its original title. 
That can cause your query to be ignored by many of the readers.)


To start a new thread, send the email to tu...@pyhon.org.

On 04/10/2013 04:57 AM, Arijit Ukil wrote:

I like to run a python program "my_python.py" from windows command
prompt. This program ( a function called testing) takes input as block
data (say data = [1,2,3,4] and outputs processed single data.

import math

def avrg(data):
 return sum(data)/len(data)

def testing (data):
 val = avrg(data)
 out = pow(val,2)
 return out



This program is missing some top-level code, so nobody is calling 
testing().  As it stands, it does nothing visible to the user.


You say the program should "take input" from the user, but there are at 
least 3 ways to do that.


1) The user could edit the source file, adding lines like:

mydata = (1, 9,43,7)
print ("results: %d" % testing(mydata) )

2) The user could put the source data into a file, such as a csv file
3) The user could have the parameters on the command line, after the 
script name.

   python my_python.py 1 9 43 7

Each of 2 and 3 require you to add some logic to process the data file 
and/or commandline.


Please specify the problem more completely, and show us what you tried, 
and somebody will probably be able to help you.


Also specify the Python version, as it can make a difference.  For 
example, avrg() function in Python 2.7 assumes either that its arguments 
include a float, or that you want only an integer result.  In Python 3, 
it'll switch to float.


--
DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Running python from windows command prompt

2013-04-10 Thread Arijit Ukil
I like to run a python program "my_python.py" from windows command prompt. 
This program ( a function called testing) takes input as block data (say 
data = [1,2,3,4] and outputs processed single data. 

import math 

def avrg(data): 
return sum(data)/len(data) 

def testing (data): 
val = avrg(data) 
out = pow(val,2) 
return out 

I am using python 2.6. My intention is to run from windows command prompt 
as

python my_python.py 1 3  2

However I am getting error: No such file in the directory, Errno 21

Pls help.

Regards,
Arijit Ukil
Tata Consultancy Services
Mailto: arijit.u...@tcs.com
Website: http://www.tcs.com

Experience certainty.   IT Services
Business Solutions
Outsourcing

=-=-=
Notice: The information contained in this e-mail
message and/or attachments to it may contain 
confidential or privileged information. If you are 
not the intended recipient, any dissemination, use, 
review, distribution, printing or copying of the 
information contained in this e-mail message 
and/or attachments to it are strictly prohibited. If 
you have received this communication in error, 
please notify us by reply e-mail or telephone and 
immediately and permanently delete the message 
and any attachments. Thank you


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running python from windows command prompt

2013-04-10 Thread Amit Saha
On Wed, Apr 10, 2013 at 10:32 PM, Arijit Ukil  wrote:
> I like to run a python program "my_python.py" from windows command prompt.
> This program ( a function called testing) takes input as block data (say
> data = [1,2,3,4] and outputs processed single data.
>
> import math
>
> def avrg(data):
>return sum(data)/len(data)
>
> def testing (data):
>val = avrg(data)
>out = pow(val,2)
>return out
>
> I am using python 2.6. My intention is to run from windows command prompt as

Why not Python 2.7 or Python 3.3 ?

>
> python my_python.py 1 3  2
>
> However I am getting error: No such file in the directory, Errno 21

Have you set the Windows Path variable correctly? Do you see IDLE in
your programs menu?

-Amit.


--
http://amitsaha.github.com/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running python from windows command prompt

2013-04-10 Thread Amit Saha
On Wed, Apr 10, 2013 at 10:32 PM, Arijit Ukil  wrote:
> I like to run a python program "my_python.py" from windows command prompt.
> This program ( a function called testing) takes input as block data (say
> data = [1,2,3,4] and outputs processed single data.
>
> import math
>
> def avrg(data):
>return sum(data)/len(data)
>
> def testing (data):
>val = avrg(data)
>out = pow(val,2)
>return out
>
> I am using python 2.6. My intention is to run from windows command prompt as
>
> python my_python.py 1 3  2

I am hoping this is not your complete program. What tutorial are you
following? Can you please paste complete programs?

-Amit.

--
http://amitsaha.github.com/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running python from windows command prompt

2013-04-10 Thread Dave Angel

On 04/10/2013 08:32 AM, Arijit Ukil wrote:

I like to run a python program "my_python.py" from windows command
prompt. This program ( a function called testing) takes input as block
data (say data = [1,2,3,4] and outputs processed single data.

import math

def avrg(data):
return sum(data)/len(data)

def testing (data):
val = avrg(data)
out = pow(val,2)
return out

I am using python 2.6. My intention is to run from windows command
prompt as

python my_python.py 1 3  2

However I am getting error: No such file in the directory, Errno 21

Pls help.



Interesting error message.  So it really doesn't identify what file, nor 
in what directory it's looking?


Windows will search the path for python, but it's up to you to specify 
the right directory for data files.


Presumably that indicates that my_python.py is not in the current 
directory.  Is it?


If that's the problem, you can either change to the right directory (cd 
 mysource)  or you can give an explicit path on the command line


python path\to\my_python.py  1 3 2

It's frequently useful to paste the relevant portion of the commandline 
into your message.  Don't paraphrase.


--
DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] File not found error, but it is in the folder!

2013-04-10 Thread Woody 544
I have a script that worked before I moved it to another folder.  I
cannot understand why I am getting a 'No such file or directory'
error, when the file is in the folder.

Any clues would be much appreciated.  Thanks!

MJ

Here is a copy and paste of the script up to the error, output/error
and a check for the file:

SCRIPT:
import os, string, codecs
os.chdir('W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS')

folder = 'W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS\\FY13Q1_responses'
files = os.listdir(folder)

#os.walk(folder)

fy13q1dict = {'country' : 'countryname', 'title':'titlename',
'travel':'traveldata',
'publications':'pubdata','conferences':'confdata','highlights':'higlightdata','upcoming':'upcomingdata'}
countryname = ()
titlename = ()

for i in files:
fy13q1dict = {'country' : 'countryname', 'title':'titlename'}
fp = codecs.open(i,mode='rb',encoding=None,errors='replace',buffering=1)
data = str(fp.read())
data = data.replace('\xa0',' ')
data = data.split()

OUTPUT:
>>>

Traceback (most recent call last):
  File "W:\BEP\DOS reports\Q1 FY13\BEP_Tool4DOS\bep_dos_tool.py", line
22, in 
fp = codecs.open(i,mode='rb',encoding=None,errors='replace',buffering=1)
  File "C:\Python27\lib\codecs.py", line 881, in open
file = __builtin__.open(filename, mode, buffering)
IOError: [Errno 2] No such file or directory: 'Algeria_688_RVF.txt'

CHECK FOR FILE IN FOLDER:
>>> os.listdir('W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS\\FY13Q1_responses')
['Algeria_688_RVF.txt', 'Egypt_31060_RVFEnvir
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Reading Program

2013-04-10 Thread bob gailer

On 4/8/2013 2:58 PM, Donald Dietrich wrote:
I am just new to python programing, but would like some help 
developing a program for "flow reading"  What I would like the program 
to do is use any  .txt file like micorsoft word .txt file and flow the 
words across the screen one at time until the file is come to the end. 
I would also like to control the rate (time) of flow. Do you think you 
can help me.

To Tutors:

I had a phone chat with Donald yesterday. Summary:
Win 8, IDLE, Python 3.1.

Working his way thru Python for Absolute Beginner.

He is seeking other books as well.

To Donald:

Here's the easiest way to create a text file:

In IDLE: File -> New Window
Enter 2 lines with 2 words on each line.
File -> Save:
  File name: test1.txt
  Save as type: Text files (*.txt)

Here's an interactive session showing some ideas:

In the Python Shell (read a file)
>>> txt = open("test1.txt")
>>> print(txt.read())
you should see the file contents here

In the Python Shell (parse the file into words)
>>> txt = open("test1.txt")
>>> print(txt.read().split())
you should see a list of the words in the file

In the Python Shell (display the words with a time delay)
>>> txt = open("test1.txt")
>>> for word in txt.read().split():
print(word)
time.sleep(.4)
now press enter again and you should see the words appear with a 0.4 
second delay.


Hope this helps get you going. Feel free to come back with questions.


--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] building a website with python

2013-04-10 Thread Bradley Cloete
On Wed, Apr 10, 2013 at 5:07 AM, Benjamin Fishbein wrote:

> >
> > You've gotten some good feedback, but I suspect you will get better
> information if you provide more information about your goals for the site.
> >
>
> Thanks for your help, everyone. There are some specific things I want the
> site to do, and I'm not sure which would be the best developing tool or
> hosting for these.
> The python software I developed is for selling used books.
> It takes book ISBN numbers as input and returns the best prices being
> offered.
> It uses the selenium module...I'm not sure how that would translate into a
> website.
> There are many websites that offer similar book price comparisons, but
> mine is different...it's user-friendly. Any volunteer at a thrift shop or
> library can use it...just a series of simple directions and yes/no
> questions, taking the user all the way from scanning or typing in an ISBN
> to dropping the parcel off at the post office. (The local libraries I
> worked with more than doubled their used-book revenues.) I want to expand
> this nationwide, and bookchicken.com seems to be the way to do it.
> So much of the program is simple enough. But there's two parts of the
> program that I anticipate being important to what host, development tool I
> use:
> 1. ISBNs (the books the thrift shop/ library has) being sent to various
> websites and returning the data to my site to be analyzed by my program.
> 2. Maneuvering through the website of the company buying the books. I
> don't want to send the user off to a warehouse's site with a list of books
> to sell to them. They'll still be entering their address and name, but
> it'll be on my site, that I then send to the warehouse's page, get a
> packing slip and shipping label from the warehouse, and give these
> documents to the user to print out.
>
> I'm not sure if this changes anyone's ideas about which host/ developer I
> should use. Please let me know.
> Thanks,
> Ben
>
>

The Django website has a list of recommended hosts.

https://code.djangoproject.com/wiki/DjangoFriendlyWebHosts

also...

http://djangohosting.com/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Phyton script for fasta file (seek help)

2013-04-10 Thread Ali Torkamani
I have written the following function for reading fasta files, I hope this
helps:

Ali

def ReadFasta(filename):

dictFasta=dict()
prevLine='';
try:

f = open(filename, "r")

for line in f:
print line
line=line.lower()
line=line.strip()
if len(line)==0: continue
if (not(line[0]>='a' and line[0]<='z')) and line[0]!='>':
continue
if line[0]=='>':
prevLine=line[1:]
dictFasta[prevLine]=''
else:
dictFasta[prevLine]=dictFasta[prevLine]+line

f.close()
except IOError:
print 'error opening %s'%(filename)
pass
return dictFasta
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] File not found error, but it is in the folder!

2013-04-10 Thread Mark Lawrence

On 10/04/2013 15:44, Woody 544 wrote:

I have a script that worked before I moved it to another folder.  I
cannot understand why I am getting a 'No such file or directory'
error, when the file is in the folder.

Any clues would be much appreciated.  Thanks!

MJ

Here is a copy and paste of the script up to the error, output/error
and a check for the file:

SCRIPT:
import os, string, codecs
os.chdir('W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS')

folder = 'W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS\\FY13Q1_responses'
files = os.listdir(folder)

#os.walk(folder)

fy13q1dict = {'country' : 'countryname', 'title':'titlename',
'travel':'traveldata',
'publications':'pubdata','conferences':'confdata','highlights':'higlightdata','upcoming':'upcomingdata'}
countryname = ()
titlename = ()

for i in files:
 fy13q1dict = {'country' : 'countryname', 'title':'titlename'}
 fp = codecs.open(i,mode='rb',encoding=None,errors='replace',buffering=1)
 data = str(fp.read())
 data = data.replace('\xa0',' ')
 data = data.split()

OUTPUT:




Traceback (most recent call last):
   File "W:\BEP\DOS reports\Q1 FY13\BEP_Tool4DOS\bep_dos_tool.py", line
22, in 
 fp = codecs.open(i,mode='rb',encoding=None,errors='replace',buffering=1)
   File "C:\Python27\lib\codecs.py", line 881, in open
 file = __builtin__.open(filename, mode, buffering)
IOError: [Errno 2] No such file or directory: 'Algeria_688_RVF.txt'

CHECK FOR FILE IN FOLDER:

os.listdir('W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS\\FY13Q1_responses')

['Algeria_688_RVF.txt', 'Egypt_31060_RVFEnvir
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



Your os.chdir call doesn't have the FY13Q1_responses directory on the end.

A slight aside, it's far easier to write Windows file paths with raw 
strings or even use forward slashes.


--
If you're using GoogleCrap™ please read this 
http://wiki.python.org/moin/GoogleGroupsPython.


Mark Lawrence

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running python from windows command prompt

2013-04-10 Thread eryksun
On Wed, Apr 10, 2013 at 8:32 AM, Arijit Ukil  wrote:
>
> python my_python.py 1 3  2

Adding Python's installation directory to PATH is for starting the
interpreter with specific options (-O, -vv, etc), running a module on
Python's sys.path (-m), running a command (-c), or starting an
interactive shell. Otherwise you can run the script directly:

my_python.py 1 3 2

With pylauncher (py.exe) installed to %WINDIR% you don't even need the
installation directory on PATH. See PEP 397.

http://www.python.org/dev/peps/pep-0397
http://bitbucket.org/vinay.sajip/pylauncher

I still add the scripts directory to PATH, which in your case might be
"C:\Python26\Scripts". I recommend you do this if you want
my_python.py to run as a command-line utility (of course you first
have to copy my_python.py to the scripts directory). You can even
avoid using the .py extension if you add .PY to the PATHEXT
environment variable.

Beyond the Windows details, your script needs to import sys and get
the argument list, sys.argv[1:]. The arguments are strings, so you'll
need to convert to float or int as required. Also, why do you import
the math module? You're not using it.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Phyton script for fasta file (seek help)

2013-04-10 Thread Danny Yoo
Hi Ali,

Again, I recommend not reinventing a FASTA parser unless you really
need something custom here.  In this particular case, the function
ReadFasta here is slow on large inputs.  The culprit is the set of
lines:

if line[0]=='>':
prevLine=line[1:]
dictFasta[prevLine]=''
else:
dictFasta[prevLine]=dictFasta[prevLine]+line
which looks innocent on its own, but it is an O(n^2) string-appending
algorithm if we walk across a very long sequence such as a
chromosome. The folks who have written the Biopython FASTA parser have
almost certainly already considered this pitfall.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Appending an extra column in a data file

2013-04-10 Thread Sayan Chatterjee
Dear All,

I have some data files with numpy arrays stored in it in 2 columns. I want
to add a third column with just floating point numbers(not numpy array) and
plot them later with Matplotlib in 3d. How is it done? Could you please
illuminate me?

Bests,
Sayan

-- 


--
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Appending an extra column in a data file

2013-04-10 Thread Andre' Walker-Loud
Hi Sayan,

This question would be better suited to the matplotlib list.
Also, a more precise description of your existing data, and what you hope it 
would look like would make it easier to help answer your question.  Eg., from 
your description, it is not clear if your existing data is in a table, and in 
the table you have numpy arrays, or if you have one numpy array of rank 2 with 
data in it.


Regards,

Andre



On Apr 10, 2013, at 8:44 AM, Sayan Chatterjee wrote:

> Dear All,
> 
> I have some data files with numpy arrays stored in it in 2 columns. I want to 
> add a third column with just floating point numbers(not numpy array) and plot 
> them later with Matplotlib in 3d. How is it done? Could you please illuminate 
> me?
> 
> Bests,
> Sayan
> 
> -- 
> 
> 
> --
> Sayan  Chatterjee
> Dept. of Physics and Meteorology
> IIT Kharagpur
> Lal Bahadur Shastry Hall of Residence
> Room AB 205
> Mob: +91 9874513565
> blog: www.blissprofound.blogspot.com
> 
> Volunteer , Padakshep
> www.padakshep.org
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] File not found error, but it is in the folder!

2013-04-10 Thread Dave Angel

On 04/10/2013 10:44 AM, Woody 544 wrote:

I have a script that worked before I moved it to another folder.  I
cannot understand why I am getting a 'No such file or directory'
error, when the file is in the folder.

Any clues would be much appreciated.  Thanks!

MJ

Here is a copy and paste of the script up to the error, output/error
and a check for the file:

SCRIPT:
import os, string, codecs
os.chdir('W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS')

folder = 'W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS\\FY13Q1_responses'
files = os.listdir(folder)

#os.walk(folder)

fy13q1dict = {'country' : 'countryname', 'title':'titlename',
'travel':'traveldata',
'publications':'pubdata','conferences':'confdata','highlights':'higlightdata','upcoming':'upcomingdata'}
countryname = ()
titlename = ()

for i in files:
 fy13q1dict = {'country' : 'countryname', 'title':'titlename'}
 fp = codecs.open(i,mode='rb',encoding=None,errors='replace',buffering=1)
 data = str(fp.read())
 data = data.replace('\xa0',' ')
 data = data.split()

OUTPUT:




Traceback (most recent call last):
   File "W:\BEP\DOS reports\Q1 FY13\BEP_Tool4DOS\bep_dos_tool.py", line
22, in 
 fp = codecs.open(i,mode='rb',encoding=None,errors='replace',buffering=1)
   File "C:\Python27\lib\codecs.py", line 881, in open
 file = __builtin__.open(filename, mode, buffering)
IOError: [Errno 2] No such file or directory: 'Algeria_688_RVF.txt'

CHECK FOR FILE IN FOLDER:

os.listdir('W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS\\FY13Q1_responses')

['Algeria_688_RVF.txt', 'Egypt_31060_RVFEnvir



As Mark points out, your problem is that you've used a different 
directory for os.chdir.


I'd like to point out that I'm heavily biased against ever changing 
"current working directory" in a non-trivial application.  The current 
directory is analogous to a global variable, and they should all be 
constant.  Now, if you want to change it once, at program entry, then 
it's like a constant that gets iniialized once.


But if you are going to use the chkdir, then all your code that deals 
with that directory should use relative paths.  If you'd done 
os.listdir(".") you'd have seen the problem.


My preference is to use absolute directories for every reference, in 
which case you'd use something like

...open(os.path.join(directory, i), ...

With of course a better name than 'i', which is traditionally an 
integer.  (since 1967, anyway)


--
DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Appending an extra column in a data file

2013-04-10 Thread Sayan Chatterjee
Thank Andre for your prompt answer.

I'll figure out the plotting issue once the dat files are made. So it's the
primary concern.
For an example I am attaching a dat file herewith. The two columns here are
2 numpy arrays.I want to add a third column, to be precise, I want to print
a parameter value on the third column of the file.

Sayan


On 10 April 2013 21:23, Andre' Walker-Loud  wrote:

> Hi Sayan,
>
> This question would be better suited to the matplotlib list.
> Also, a more precise description of your existing data, and what you hope
> it would look like would make it easier to help answer your question.  Eg.,
> from your description, it is not clear if your existing data is in a table,
> and in the table you have numpy arrays, or if you have one numpy array of
> rank 2 with data in it.
>
>
> Regards,
>
> Andre
>
>
>
> On Apr 10, 2013, at 8:44 AM, Sayan Chatterjee wrote:
>
> > Dear All,
> >
> > I have some data files with numpy arrays stored in it in 2 columns. I
> want to add a third column with just floating point numbers(not numpy
> array) and plot them later with Matplotlib in 3d. How is it done? Could you
> please illuminate me?
> >
> > Bests,
> > Sayan
> >
> > --
> >
> >
> >
> --
> > Sayan  Chatterjee
> > Dept. of Physics and Meteorology
> > IIT Kharagpur
> > Lal Bahadur Shastry Hall of Residence
> > Room AB 205
> > Mob: +91 9874513565
> > blog: www.blissprofound.blogspot.com
> >
> > Volunteer , Padakshep
> > www.padakshep.org
> > ___
> > Tutor maillist  -  Tutor@python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
>
>


-- 


--
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org


file_0.02.dat
Description: Binary data
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Appending an extra column in a data file

2013-04-10 Thread Andre' Walker-Loud
Hi Sayan,

> Thank Andre for your prompt answer. 

No problem.

> I'll figure out the plotting issue once the dat files are made. So it's the 
> primary concern.
> For an example I am attaching a dat file herewith. The two columns here are 2 
> numpy arrays.I want to add a third column, to be precise, I want to print a 
> parameter value on the third column of the file.

Let me try again.
The reason the matplotlib list would be a better place is this is a general 
python list, and most people are not familiar with numpy.  However, most people 
who use matplotlib are familiar with numpy.

I am hoping you can describe precisely the structure of the data.  Maybe show a 
little code on how it is created, or how you access it.  I am not keen to open 
"random" files from the internet.  As two examples of how I think your code 
might be packed

1/
'''
x = numpy.zeros([10]) # 1D numpy array of dimension 10
y = numpy.zeros([10]) # 1D numpy array of dimension 10
your_data = []
your_data.append(x)
your_data.append(y)
'''

so now your data is a table with two entries, and each entry is a numpy array.
You have in mind adding a third entry to the table with just floats.

2/
'''
your_data = numpy.zeros([10,10]) # initialize a 2D numpy array with all zeros
for i in range(your_data.shape[0]):
for j in range(your_data.shape[1]):
your_data[i,j] = data[i][j] # I am assuming the data is imported 
already and called data and is in a python list/table format
'''

Now you want to make a new column or row for your data file, which contains 
floats.  Well, all the entries inside the numpy array are already floats, so it 
is not clear to me why you want a new column that is not a numpy array. So it 
would be nice if you could precisely describe what you currently have and what 
you want.


Hope this helps,

Andre


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running python from windows command prompt

2013-04-10 Thread Alan Gauld

On 10/04/13 13:32, Arijit Ukil wrote:

I like to run a python program "my_python.py" from windows command
prompt. This program ( a function called testing) takes input as block
data (say data = [1,2,3,4] and outputs processed single data.



Hopefully the code below is not your entire program. If it is it won't 
work. You define 2 functions but never call them.


Also you don't print anything so there is no visible output.
Finally this a code does not read the values from sys.argv.
(See my tutorial topic 'Talking to the user')

As for the error message, others have replied but basically you need
to either change to the folder that your file exists in or specify
the full path at the command prompt.


import math

def avrg(data):
return sum(data)/len(data)

def testing (data):
val = avrg(data)
out = pow(val,2)
return out


HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Appending an extra column in a data file

2013-04-10 Thread Sayan Chatterjee
Hi Andre,

Well,this is the concerned snippet of the code:


while *t < 1*:


  pp_za = pp_init + t*K*np.sin(K*pp_init)

# Periodic Boundary Condition

  for i in range(0,999):

if pp_za[i] < 0:
  pp_za[i] = 2 - abs(pp_za[i])
if pp_za[i] > 2:
  pp_za[i] = pp_za[i] % 2

  pv_za = +K*np.sin(K*pp_init)

  fname = 'file_' + str(t) + '.dat'

# Generating dataset for Phase Space diagram

  *np.savetxt(fname, np.array([pp_za,pv_za]).T, '%f')*

  t = t + 0.01

And the sample data generated is :

0.105728 0.098678
0.126865 0.118406
0.147998 0.138128
0.169126 0.157845
0.190247 0.177556
0.211362 0.197259
0.232469 0.216955
0.253567 0.236643
0.274657 0.256321
0.295737 0.275989
0.316806 0.295646

Precisely what I want is, I want to add the 't' (over which the while loop
is run) in the 3 rd column. 't' is float and constant for each looping. If
you know what a phase plot is(doesn't matter if you don't), I want to see
the phase plot evolving with time. Thus the need of a time axis and hence
plot with V(velocity-Yaxis), X ( Position -X axis) and t (Time-Z axis).

I hope your first example might help.Though,I think,I need some tweaking to
fit to my needs.

Regards,
Sayan


On 10 April 2013 22:38, Andre' Walker-Loud  wrote:

> Hi Sayan,
>
> > Thank Andre for your prompt answer.
>
> No problem.
>
> > I'll figure out the plotting issue once the dat files are made. So it's
> the primary concern.
> > For an example I am attaching a dat file herewith. The two columns here
> are 2 numpy arrays.I want to add a third column, to be precise, I want to
> print a parameter value on the third column of the file.
>
> Let me try again.
> The reason the matplotlib list would be a better place is this is a
> general python list, and most people are not familiar with numpy.  However,
> most people who use matplotlib are familiar with numpy.
>
> I am hoping you can describe precisely the structure of the data.  Maybe
> show a little code on how it is created, or how you access it.  I am not
> keen to open "random" files from the internet.  As two examples of how I
> think your code might be packed
>
> 1/
> '''
> x = numpy.zeros([10]) # 1D numpy array of dimension 10
> y = numpy.zeros([10]) # 1D numpy array of dimension 10
> your_data = []
> your_data.append(x)
> your_data.append(y)
> '''
>
> so now your data is a table with two entries, and each entry is a numpy
> array.
> You have in mind adding a third entry to the table with just floats.
>
> 2/
> '''
> your_data = numpy.zeros([10,10]) # initialize a 2D numpy array with all
> zeros
> for i in range(your_data.shape[0]):
> for j in range(your_data.shape[1]):
> your_data[i,j] = data[i][j] # I am assuming the data is imported
> already and called data and is in a python list/table format
> '''
>
> Now you want to make a new column or row for your data file, which
> contains floats.  Well, all the entries inside the numpy array are already
> floats, so it is not clear to me why you want a new column that is not a
> numpy array. So it would be nice if you could precisely describe what you
> currently have and what you want.
>
>
> Hope this helps,
>
> Andre
>
>
>


-- 


--
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Appending an extra column in a data file

2013-04-10 Thread Alan Gauld

On 10/04/13 16:44, Sayan Chatterjee wrote:


I have some data files with numpy arrays stored in it in 2 columns. I


Can you define what that means?
All files on a computer are data files in some sense.
They exist as text files or binary files. If they are text files then 
the content of your arrays must be encoded somehow as strings. If they 
are binary files you must have dumped them to file somehow and adding 
floats is something you probably need to figure out yourself!


How did you create these files? (Or how were they created buy somebody 
else?)



want to add a third column with just floating point numbers(not numpy
array) and plot them later with Matplotlib in 3d. How is it done? Could
you please illuminate me?


The fact you use the term column suggests that maybe they are text files 
of some kind in which case you likely have the content of the numpy 
arrays but not their structure, in which case adding an extra column 
should be easy by following the pattern of how you created the files. 
Don't forget to modify the functions that read the data back to match.


But with no idea of the exact nature of your "data files" we can't give 
very specific help.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Appending an extra column in a data file

2013-04-10 Thread Andre' Walker-Loud
Hi Sayan,

> Well,this is the concerned snippet of the code:
> 
> 
> while t < 1:
> 
>   
>   pp_za = pp_init + t*K*np.sin(K*pp_init)
>   
> # Periodic Boundary Condition
>   
>   for i in range(0,999):
> 
> if pp_za[i] < 0:
>   pp_za[i] = 2 - abs(pp_za[i])
> if pp_za[i] > 2:
>   pp_za[i] = pp_za[i] % 2 
> 
>   pv_za = +K*np.sin(K*pp_init)
>   
>   fname = 'file_' + str(t) + '.dat'
> 
> # Generating dataset for Phase Space diagram
> 
>   np.savetxt(fname, np.array([pp_za,pv_za]).T, '%f')
>   
>   t = t + 0.01

To answer your question, to add "t" to the array, you can simply replace the 
current np.array command with either of the following

np.array([pp_za,pv_za,t])

or 

np.array([t,pp_za,pv_za])

depending if you want "t" is the first element of the data or the last.
Also, you are "transposing" the array with the ".T", so this will write the 
data in sequential lines, rather than a single line (row) with multiple 
entries.  I just bring it up because it is not the "obvious" way to pack the 
data.

Also, it looks like you are generating a separate file for each "t".
Is this what you want?
I assume you want a single data file that stores this info, not many data files.


Andre





> 
> And the sample data generated is : 
> 
> 0.105728 0.098678
> 0.126865 0.118406
> 0.147998 0.138128
> 0.169126 0.157845
> 0.190247 0.177556
> 0.211362 0.197259
> 0.232469 0.216955
> 0.253567 0.236643
> 0.274657 0.256321
> 0.295737 0.275989
> 0.316806 0.295646
> 
> Precisely what I want is, I want to add the 't' (over which the while loop is 
> run) in the 3 rd column. 't' is float and constant for each looping. If you 
> know what a phase plot is(doesn't matter if you don't), I want to see the 
> phase plot evolving with time. Thus the need of a time axis and hence plot 
> with V(velocity-Yaxis), X ( Position -X axis) and t (Time-Z axis).
> 
> I hope your first example might help.Though,I think,I need some tweaking to 
> fit to my needs.
> 
> Regards,
> Sayan
> 
> 
> On 10 April 2013 22:38, Andre' Walker-Loud  wrote:
> Hi Sayan,
> 
> > Thank Andre for your prompt answer.
> 
> No problem.
> 
> > I'll figure out the plotting issue once the dat files are made. So it's the 
> > primary concern.
> > For an example I am attaching a dat file herewith. The two columns here are 
> > 2 numpy arrays.I want to add a third column, to be precise, I want to print 
> > a parameter value on the third column of the file.
> 
> Let me try again.
> The reason the matplotlib list would be a better place is this is a general 
> python list, and most people are not familiar with numpy.  However, most 
> people who use matplotlib are familiar with numpy.
> 
> I am hoping you can describe precisely the structure of the data.  Maybe show 
> a little code on how it is created, or how you access it.  I am not keen to 
> open "random" files from the internet.  As two examples of how I think your 
> code might be packed
> 
> 1/
> '''
> x = numpy.zeros([10]) # 1D numpy array of dimension 10
> y = numpy.zeros([10]) # 1D numpy array of dimension 10
> your_data = []
> your_data.append(x)
> your_data.append(y)
> '''
> 
> so now your data is a table with two entries, and each entry is a numpy array.
> You have in mind adding a third entry to the table with just floats.
> 
> 2/
> '''
> your_data = numpy.zeros([10,10]) # initialize a 2D numpy array with all zeros
> for i in range(your_data.shape[0]):
> for j in range(your_data.shape[1]):
> your_data[i,j] = data[i][j] # I am assuming the data is imported 
> already and called data and is in a python list/table format
> '''
> 
> Now you want to make a new column or row for your data file, which contains 
> floats.  Well, all the entries inside the numpy array are already floats, so 
> it is not clear to me why you want a new column that is not a numpy array. So 
> it would be nice if you could precisely describe what you currently have and 
> what you want.
> 
> 
> Hope this helps,
> 
> Andre
> 
> 
> 
> 
> 
> -- 
> 
> 
> --
> Sayan  Chatterjee
> Dept. of Physics and Meteorology
> IIT Kharagpur
> Lal Bahadur Shastry Hall of Residence
> Room AB 205
> Mob: +91 9874513565
> blog: www.blissprofound.blogspot.com
> 
> Volunteer , Padakshep
> www.padakshep.org

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Appending an extra column in a data file

2013-04-10 Thread Sayan Chatterjee
Hi Alan,

Sorry for the ambiguity I have created.

 I have added the snippet of code just in the previous mail and also the
sample data in the text file. Have you had a look on them?

I am copy pasting it in this email:

Hi Andre,

Well,this is the concerned snippet of the code:


while *t < 1*:


  pp_za = pp_init + t*K*np.sin(K*pp_init)

# Periodic Boundary Condition

  for i in range(0,999):

if pp_za[i] < 0:
  pp_za[i] = 2 - abs(pp_za[i])
if pp_za[i] > 2:
  pp_za[i] = pp_za[i] % 2

  pv_za = +K*np.sin(K*pp_init)

  fname = 'file_' + str(t) + '.dat'

# Generating dataset for Phase Space diagram

  *np.savetxt(fname, np.array([pp_za,pv_za]).T, '%f')*

  t = t + 0.01

And the sample data generated is :

0.105728 0.098678
0.126865 0.118406
0.147998 0.138128
0.169126 0.157845
0.190247 0.177556
0.211362 0.197259
0.232469 0.216955
0.253567 0.236643
0.274657 0.256321
0.295737 0.275989
0.316806 0.295646

Precisely what I want is, I want to add the 't' (over which the while loop
is run) in the 3 rd column. 't' is float and constant for each looping. If
you know what a phase plot is(doesn't matter if you don't), I want to see
the phase plot evolving with time. Thus the need of a time axis and hence
plot with V(velocity-Yaxis), X ( Position -X axis) and t (Time-Z axis).


Regards,
Sayan




On 10 April 2013 23:07, Alan Gauld  wrote:

> On 10/04/13 16:44, Sayan Chatterjee wrote:
>
>  I have some data files with numpy arrays stored in it in 2 columns. I
>>
>
> Can you define what that means?
> All files on a computer are data files in some sense.
> They exist as text files or binary files. If they are text files then the
> content of your arrays must be encoded somehow as strings. If they are
> binary files you must have dumped them to file somehow and adding floats is
> something you probably need to figure out yourself!
>
> How did you create these files? (Or how were they created buy somebody
> else?)
>
>
>  want to add a third column with just floating point numbers(not numpy
>> array) and plot them later with Matplotlib in 3d. How is it done? Could
>> you please illuminate me?
>>
>
> The fact you use the term column suggests that maybe they are text files
> of some kind in which case you likely have the content of the numpy arrays
> but not their structure, in which case adding an extra column should be
> easy by following the pattern of how you created the files. Don't forget to
> modify the functions that read the data back to match.
>
> But with no idea of the exact nature of your "data files" we can't give
> very specific help.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>



-- 


--
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] building a website with python

2013-04-10 Thread Don Jennings

On Apr 9, 2013, at 11:07 PM, Benjamin Fishbein wrote:

>> 
>> You've gotten some good feedback, but I suspect you will get better 
>> information if you provide more information about your goals for the site.
>> 
> 
> Thanks for your help, everyone. There are some specific things I want the 
> site to do, and I'm not sure which would be the best developing tool or 
> hosting for these.
> The python software I developed is for selling used books.
> It takes book ISBN numbers as input and returns the best prices being offered.
> It uses the selenium module...I'm not sure how that would translate into a 
> website.

Checking the documentation [1], selenium will interact with a browser running 
remotely using the selenium-server. However, I don't imagine the latter option 
being viable if you plan to have any significant traffic. I would think a 
better plan is to forego the gui browser, perhaps re-writing the interaction 
with other sites using requests [2], a very nice way to work with HTTP. Do you 
need to interact with javascript on those pages?

> There are many websites that offer similar book price comparisons, but mine 
> is different...it's user-friendly. Any volunteer at a thrift shop or library 
> can use it...just a series of simple directions and yes/no questions, taking 
> the user all the way from scanning or typing in an ISBN to dropping the 
> parcel off at the post office. (The local libraries I worked with more than 
> doubled their used-book revenues.) I want to expand this nationwide, and 
> bookchicken.com seems to be the way to do it.
> So much of the program is simple enough. But there's two parts of the program 
> that I anticipate being important to what host, development tool I use:
> 1. ISBNs (the books the thrift shop/ library has) being sent to various 
> websites and returning the data to my site to be analyzed by my program.
> 2. Maneuvering through the website of the company buying the books. I don't 
> want to send the user off to a warehouse's site with a list of books to sell 
> to them. They'll still be entering their address and name, but it'll be on my 
> site, that I then send to the warehouse's page, get a packing slip and 
> shipping label from the warehouse, and give these documents to the user to 
> print out.
> 
> I'm not sure if this changes anyone's ideas about which host/ developer I 
> should use. Please let me know.

Obviously my recommendations for producing a static site missed the mark! I do 
think that one of the microframeworks folks have mentioned will get you up and 
running faster.

Take care,
Don

[1] http://docs.seleniumhq.org/docs/03_webdriver.jsp
[2] http://docs.python-requests.org/en/latest/user/quickstart/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Appending an extra column in a data file

2013-04-10 Thread Sayan Chatterjee
Yup it's exactly what I want!

I want *many* data files,not one...to make an animation out of it. For a
data file t is constant.

the solution you have just mentioned i.e np.array([t,pp_za,pv_za]) is
giving the following error:


Traceback (most recent call last):
  File "ZA_Phase_Plot.py", line 38, in 
np.savetxt(fname, np.array([pp_za,pv_za,t]).T, '%f')
  File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 979, in
savetxt
fh.write(asbytes(format % tuple(row) + newline))
TypeError: float argument required, not numpy.ndarray

What to do? :-|

Sayan



On 10 April 2013 23:17, Andre' Walker-Loud  wrote:

> Hi Sayan,
>
> > Well,this is the concerned snippet of the code:
> >
> >
> > while t < 1:
> >
> >
> >   pp_za = pp_init + t*K*np.sin(K*pp_init)
> >
> > # Periodic Boundary Condition
> >
> >   for i in range(0,999):
> >
> > if pp_za[i] < 0:
> >   pp_za[i] = 2 - abs(pp_za[i])
> > if pp_za[i] > 2:
> >   pp_za[i] = pp_za[i] % 2
> >
> >   pv_za = +K*np.sin(K*pp_init)
> >
> >   fname = 'file_' + str(t) + '.dat'
> >
> > # Generating dataset for Phase Space diagram
> >
> >   np.savetxt(fname, np.array([pp_za,pv_za]).T, '%f')
> >
> >   t = t + 0.01
>
> To answer your question, to add "t" to the array, you can simply replace
> the current np.array command with either of the following
>
> np.array([pp_za,pv_za,t])
>
> or
>
> np.array([t,pp_za,pv_za])
>
> depending if you want "t" is the first element of the data or the last.
> Also, you are "transposing" the array with the ".T", so this will write
> the data in sequential lines, rather than a single line (row) with multiple
> entries.  I just bring it up because it is not the "obvious" way to pack
> the data.
>
> Also, it looks like you are generating a separate file for each "t".
> Is this what you want?
> I assume you want a single data file that stores this info, not many data
> files.
>
>
> Andre
>
>
>
>
>
> >
> > And the sample data generated is :
> >
> > 0.105728 0.098678
> > 0.126865 0.118406
> > 0.147998 0.138128
> > 0.169126 0.157845
> > 0.190247 0.177556
> > 0.211362 0.197259
> > 0.232469 0.216955
> > 0.253567 0.236643
> > 0.274657 0.256321
> > 0.295737 0.275989
> > 0.316806 0.295646
> >
> > Precisely what I want is, I want to add the 't' (over which the while
> loop is run) in the 3 rd column. 't' is float and constant for each
> looping. If you know what a phase plot is(doesn't matter if you don't), I
> want to see the phase plot evolving with time. Thus the need of a time axis
> and hence plot with V(velocity-Yaxis), X ( Position -X axis) and t (Time-Z
> axis).
> >
> > I hope your first example might help.Though,I think,I need some tweaking
> to fit to my needs.
> >
> > Regards,
> > Sayan
> >
> >
> > On 10 April 2013 22:38, Andre' Walker-Loud  wrote:
> > Hi Sayan,
> >
> > > Thank Andre for your prompt answer.
> >
> > No problem.
> >
> > > I'll figure out the plotting issue once the dat files are made. So
> it's the primary concern.
> > > For an example I am attaching a dat file herewith. The two columns
> here are 2 numpy arrays.I want to add a third column, to be precise, I want
> to print a parameter value on the third column of the file.
> >
> > Let me try again.
> > The reason the matplotlib list would be a better place is this is a
> general python list, and most people are not familiar with numpy.  However,
> most people who use matplotlib are familiar with numpy.
> >
> > I am hoping you can describe precisely the structure of the data.  Maybe
> show a little code on how it is created, or how you access it.  I am not
> keen to open "random" files from the internet.  As two examples of how I
> think your code might be packed
> >
> > 1/
> > '''
> > x = numpy.zeros([10]) # 1D numpy array of dimension 10
> > y = numpy.zeros([10]) # 1D numpy array of dimension 10
> > your_data = []
> > your_data.append(x)
> > your_data.append(y)
> > '''
> >
> > so now your data is a table with two entries, and each entry is a numpy
> array.
> > You have in mind adding a third entry to the table with just floats.
> >
> > 2/
> > '''
> > your_data = numpy.zeros([10,10]) # initialize a 2D numpy array with all
> zeros
> > for i in range(your_data.shape[0]):
> > for j in range(your_data.shape[1]):
> > your_data[i,j] = data[i][j] # I am assuming the data is imported
> already and called data and is in a python list/table format
> > '''
> >
> > Now you want to make a new column or row for your data file, which
> contains floats.  Well, all the entries inside the numpy array are already
> floats, so it is not clear to me why you want a new column that is not a
> numpy array. So it would be nice if you could precisely describe what you
> currently have and what you want.
> >
> >
> > Hope this helps,
> >
> > Andre
> >
> >
> >
> >
> >
> > --
> >
> >
> >
> --
> > Sayan  Chatterjee
> > Dept. of Physics and Meteorology
> > IIT Kharagpur
> > Lal Bahadur Shastry Hall o

Re: [Tutor] Phyton script for fasta file (seek help)

2013-04-10 Thread Ali Torkamani
On Wed, Apr 10, 2013 at 8:32 AM, Danny Yoo  wrote:

> Hi Ali,
>
> Again, I recommend not reinventing a FASTA parser unless you really
> need something custom here.  In this particular case, the function
> ReadFasta here is slow on large inputs.  The culprit is the set of
> lines:
>
> if line[0]=='>':
> prevLine=line[1:]
> dictFasta[prevLine]=''
> else:
>

Sure, I myself use biopythin as well, but just wanted to mention that it's
not a big hassle, in particular if you need to load it just once. You have
a very legitimate point about the order of execution of my suggested code.

Ali
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] File not found error, but it is in the folder!

2013-04-10 Thread eryksun
On Wed, Apr 10, 2013 at 12:22 PM, Dave Angel  wrote:
> My preference is to use absolute directories for every reference, in which
> case you'd use something like
> ...open(os.path.join(directory, i), ...

+1

> With of course a better name than 'i', which is traditionally an integer.
> (since 1967, anyway)

At least 1958. I'm not familiar with pre-77 FORTRAN, but I found an
old manual for FORTRAN II on UNIVAC systems, written by Knuth in 1962.
 It states that any variable name starting with the letters I through
N is implicitly typed integer; otherwise it's implicitly a float.
FORTRAN 77 introduced "IMPLICIT NONE" to disable this feature.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Appending an extra column in a data file

2013-04-10 Thread Andre' Walker-Loud
Hi Sayan,

> Yup it's exactly what I want!
> 
> I want many data files,not one...to make an animation out of it. For a data 
> file t is constant.

You should not need many data files to make an animation.  If you write your 
loops correctly, you can take a single data file with all the data.  If you are 
using code you did not write, and just want to get it to work, I understand 
that, but would encourage you also to figure out how to do it all with single 
data file.  Less files makes a files system and user happier.

> the solution you have just mentioned i.e np.array([t,pp_za,pv_za]) is giving 
> the following error:
> 
> 
> Traceback (most recent call last):
>   File "ZA_Phase_Plot.py", line 38, in 
> np.savetxt(fname, np.array([pp_za,pv_za,t]).T, '%f')
>   File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 979, in 
> savetxt
> fh.write(asbytes(format % tuple(row) + newline))
> TypeError: float argument required, not numpy.ndarray
> 
> What to do? :-|

There are pieces of the code snipet you sent which are not defined, so it is 
not clear why you are getting this error.  How long is the file 
"ZA_Phase_Plot.py"?  At least you can send from line 0 to where you did before, 
so all the variables are defined.  That should help.

Andre



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Appending an extra column in a data file

2013-04-10 Thread Sayan Chatterjee
Hi Andre,

Is it that? We can have different plots and hence animation from a single
data file.Very good!...if you have some time in your disposal, it will be
kind of you to illumine in this matter...may be some useful link will do.

I have written this small code from scratch,there's no 'get it to work'
business...:)

Here is the total code...not attaching as you might have problem opening
random files from internet:)

#!usr/bin/python

import numpy as np
import matplotlib.pyplot as plt
import itertools as i
import pylab

K = 3.14
t = 0

# Allotment of particles

pp_init = np.linspace(0,1.99799799,999)

print pp_init

# Velocity array

while t < 1:


  pp_za = pp_init + t*K*np.sin(K*pp_init)

# Periodic Boundary Condition

  for i in range(0,999):

if pp_za[i] < 0:
  pp_za[i] = 2 - abs(pp_za[i])
if pp_za[i] > 2:
  pp_za[i] = pp_za[i] % 2

  pv_za = +K*np.sin(K*pp_init)

  fname = 'file_' + str(t) + '.dat'

# Generating dataset for Phase Space diagram
  np.savetxt(fname, np.array([pp_za,pv_za,t]), '%f')

  t = t + 0.01

# Plot using Matplotlib

i = 0

while i < 1:
  fname = 'file_' + str(i) + '.dat'
  f=open(fname,"r")
  x,y = np.loadtxt(fname, unpack=True)
  #plt.plot(x,y,linewidth=2.0)
  plt.scatter(x,y)
  plt.ylim(-8,8)
  plt.xlim(0,2)
  plt.ylabel('Velocity')
  plt.xlabel('X')
  pylab.savefig(fname + '.png')
  plt.cla()
  f.close()
  i = i  + 0.001

Regards,
Sayan




On 10 April 2013 23:36, Andre' Walker-Loud  wrote:

> Hi Sayan,
>
> > Yup it's exactly what I want!
> >
> > I want many data files,not one...to make an animation out of it. For a
> data file t is constant.
>
> You should not need many data files to make an animation.  If you write
> your loops correctly, you can take a single data file with all the data.
>  If you are using code you did not write, and just want to get it to work,
> I understand that, but would encourage you also to figure out how to do it
> all with single data file.  Less files makes a files system and user
> happier.
>
> > the solution you have just mentioned i.e np.array([t,pp_za,pv_za]) is
> giving the following error:
> >
> >
> > Traceback (most recent call last):
> >   File "ZA_Phase_Plot.py", line 38, in 
> > np.savetxt(fname, np.array([pp_za,pv_za,t]).T, '%f')
> >   File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 979,
> in savetxt
> > fh.write(asbytes(format % tuple(row) + newline))
> > TypeError: float argument required, not numpy.ndarray
> >
> > What to do? :-|
>
> There are pieces of the code snipet you sent which are not defined, so it
> is not clear why you are getting this error.  How long is the file
> "ZA_Phase_Plot.py"?  At least you can send from line 0 to where you did
> before, so all the variables are defined.  That should help.
>
> Andre
>
>
>
>


-- 


--
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Appending an extra column in a data file

2013-04-10 Thread Oscar Benjamin
On 10 April 2013 17:58, Sayan Chatterjee  wrote:
> Thank Andre for your prompt answer.
>
> I'll figure out the plotting issue once the dat files are made. So it's the
> primary concern.
> For an example I am attaching a dat file herewith. The two columns here are
> 2 numpy arrays.I want to add a third column, to be precise, I want to print
> a parameter value on the third column of the file.

The file you attached is a space-delimited text file. If you want to
add a third column with the value '1.0' on every row you can just do:

with open('old.dat') as fin, open('new.dat', 'w') as fout:
for line in fin:
fout.write(line[:-1] + ' 1.0\n')


Oscar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Appending an extra column in a data file

2013-04-10 Thread Sayan Chatterjee
Hi Andre,

I figured it out. Need not reply of np.savetxt for storing array simply
f.wite() is doing fine.

while i < 999:
print i
fo.write('{0:f}  {1:f}  {2:f}\n'.format(pp_za[i], pv_za[i],t))
i = i + 1

Eager to know that single file thing though!

Sayan


On 10 April 2013 23:52, Sayan Chatterjee  wrote:

> Hi Andre,
>
> Is it that? We can have different plots and hence animation from a single
> data file.Very good!...if you have some time in your disposal, it will be
> kind of you to illumine in this matter...may be some useful link will do.
>
> I have written this small code from scratch,there's no 'get it to work'
> business...:)
>
> Here is the total code...not attaching as you might have problem opening
> random files from internet:)
>
> #!usr/bin/python
>
> import numpy as np
> import matplotlib.pyplot as plt
> import itertools as i
> import pylab
>
> K = 3.14
> t = 0
>
> # Allotment of particles
>
> pp_init = np.linspace(0,1.99799799,999)
>
> print pp_init
>
> # Velocity array
>
> while t < 1:
>
>
>   pp_za = pp_init + t*K*np.sin(K*pp_init)
>
> # Periodic Boundary Condition
>
>   for i in range(0,999):
>
> if pp_za[i] < 0:
>   pp_za[i] = 2 - abs(pp_za[i])
> if pp_za[i] > 2:
>   pp_za[i] = pp_za[i] % 2
>
>   pv_za = +K*np.sin(K*pp_init)
>
>   fname = 'file_' + str(t) + '.dat'
>
> # Generating dataset for Phase Space diagram
>   np.savetxt(fname, np.array([pp_za,pv_za,t]), '%f')
>
>   t = t + 0.01
>
> # Plot using Matplotlib
>
> i = 0
>
> while i < 1:
>   fname = 'file_' + str(i) + '.dat'
>   f=open(fname,"r")
>   x,y = np.loadtxt(fname, unpack=True)
>   #plt.plot(x,y,linewidth=2.0)
>   plt.scatter(x,y)
>   plt.ylim(-8,8)
>   plt.xlim(0,2)
>   plt.ylabel('Velocity')
>   plt.xlabel('X')
>   pylab.savefig(fname + '.png')
>   plt.cla()
>   f.close()
>   i = i  + 0.001
>
> Regards,
> Sayan
>
>
>
>
> On 10 April 2013 23:36, Andre' Walker-Loud  wrote:
>
>> Hi Sayan,
>>
>> > Yup it's exactly what I want!
>> >
>> > I want many data files,not one...to make an animation out of it. For a
>> data file t is constant.
>>
>> You should not need many data files to make an animation.  If you write
>> your loops correctly, you can take a single data file with all the data.
>>  If you are using code you did not write, and just want to get it to work,
>> I understand that, but would encourage you also to figure out how to do it
>> all with single data file.  Less files makes a files system and user
>> happier.
>>
>> > the solution you have just mentioned i.e np.array([t,pp_za,pv_za]) is
>> giving the following error:
>> >
>> >
>> > Traceback (most recent call last):
>> >   File "ZA_Phase_Plot.py", line 38, in 
>> > np.savetxt(fname, np.array([pp_za,pv_za,t]).T, '%f')
>> >   File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 979,
>> in savetxt
>> > fh.write(asbytes(format % tuple(row) + newline))
>> > TypeError: float argument required, not numpy.ndarray
>> >
>> > What to do? :-|
>>
>> There are pieces of the code snipet you sent which are not defined, so it
>> is not clear why you are getting this error.  How long is the file
>> "ZA_Phase_Plot.py"?  At least you can send from line 0 to where you did
>> before, so all the variables are defined.  That should help.
>>
>> Andre
>>
>>
>>
>>
>
>
> --
>
>
> --
> *Sayan  Chatterjee*
> Dept. of Physics and Meteorology
> IIT Kharagpur
> Lal Bahadur Shastry Hall of Residence
> Room AB 205
> Mob: +91 9874513565
> blog: www.blissprofound.blogspot.com
>
> Volunteer , Padakshep
> www.padakshep.org
>



-- 


--
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Appending an extra column in a data file

2013-04-10 Thread Sayan Chatterjee
Thanks Oscar figured it out...:)


On 11 April 2013 00:17, Oscar Benjamin  wrote:

> On 10 April 2013 17:58, Sayan Chatterjee 
> wrote:
> > Thank Andre for your prompt answer.
> >
> > I'll figure out the plotting issue once the dat files are made. So it's
> the
> > primary concern.
> > For an example I am attaching a dat file herewith. The two columns here
> are
> > 2 numpy arrays.I want to add a third column, to be precise, I want to
> print
> > a parameter value on the third column of the file.
>
> The file you attached is a space-delimited text file. If you want to
> add a third column with the value '1.0' on every row you can just do:
>
> with open('old.dat') as fin, open('new.dat', 'w') as fout:
> for line in fin:
> fout.write(line[:-1] + ' 1.0\n')
>
>
> Oscar
>



-- 


--
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Appending an extra column in a data file

2013-04-10 Thread Oscar Benjamin
On 10 April 2013 19:48, Sayan Chatterjee  wrote:
> Hi Andre,
>
> I figured it out. Need not reply of np.savetxt for storing array simply
> f.wite() is doing fine.
>
> while i < 999:
> print i
> fo.write('{0:f}  {1:f}  {2:f}\n'.format(pp_za[i], pv_za[i],t))
> i = i + 1
>
> Eager to know that single file thing though!

The animation module in matplotlib can do animations for you without
you needing to explicitly write your data out to files. The code below
is taken from some matplotlib documentation or wiki. I don't remember
exactly where I got it from but I do remember that I needed to modify
it slightly to get it to work. If you run the script it will create
200 png image files and then call an external program (mencoder or
ffmpeg - need to install those separately) to convert the png files
into an mp4 video file.

#!/usr/bin/env python
"""
Matplotlib Animation Example

author: Jake Vanderplas
email: vanderp...@astro.washington.edu
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,

# animation function.  This is called sequentially
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i))
line.set_data(x, y)
return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
   frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('./basic_animation.mp4', fps=30)


Oscar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Appending an extra column in a data file

2013-04-10 Thread Andre' Walker-Loud
Hi Sayan,

> Is it that? We can have different plots and hence animation from a single 
> data file.Very good!...if you have some time in your disposal, it will be 
> kind of you to illumine in this matter...may be some useful link will do.
> 
> I have written this small code from scratch,there's no 'get it to work' 
> business...:)
> 
> Here is the total code...not attaching as you might have problem opening 
> random files from internet:)

I will leave the complete code snippet for the list memory.
A couple things.

With the code you have now, you do not even have to save any files.  You can 
simply implant the plotting into the initial while loop.  Right now, your saved 
files serve only as a temporary holding file for the data you had just created. 
 Since your initial data is not read from another file, but simply generated in 
your code, there is no reason to write any thing to disk, except the figures 
you are saving.

One thing to notice, your "t" and "i" while loops iterate over different 
counters.  You have
t = t + 0.01
i = i + 0.001
so your second loop will produce many calls that don't match anything (the 
files you created don't exist).

The previous error is because the pp_za and pv_za are already 1D numpy arrays 
of dimension 999.  That is why combining them with a single float, 
"np.array([pp_za,pv_za,t])", did not work - the dimension of "pp_za" and "t" 
don't match, so writing them with numpy.savetxt() gave an error.

How do you want to include the "t" information in the figure?
Do you want to make different plots with a time axis?  Or, it sounds like you 
are talking about a 3D plot?

If you want to store the time with the data, then make a t_array like so

''' inside your t while loop '''
# make an array filled with ones the same dimension as your pp_init, and then 
multiply each entry by "t"
t_array = t * numpy.ones_like(pp_init) 

''' then pack your data as '''
np.array([pp_za,pv_za,t_array])

but to have a single data file containing all of this:

t_array = np.arange(0,1,.001) # initialize all the times you care about
pp_init = np.linspace(0,1.99799799,999)  #just taking from your code
# initialize an array of zeros
# first dimension spans time
# second dimension is 3 to store value of pp_za, pv_za, t
# third dimension is actual length of data
all_data = np.zeros([len(t_array),3,len(pp_init)]) 

for i,t in enumerate(t_array):
# make your pp_za and pv_za as in your code
t_tmp = t * numpy.ones_like(pp_init)
all_data[i] = np.array([pp_za,pv_za,t])


'''
now you have a single object (np.array) which contains all of your data.
You could either make each of the figures in the above loop, or you can use a 
second loop to make them.
I see Oscar has given you some advice on the plotting - so you could use this 
single object and his example to do what you want.


Andre


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Appending an extra column in a data file

2013-04-10 Thread Albert-Jan Roskam


> Subject: Re: [Tutor] Appending an extra column in a data file
> 

 
> The file you attached is a space-delimited text file. If you want to
> add a third column with the value '1.0' on every row you can just do:
> 
> with open('old.dat') as fin, open('new.dat', 'w') as 
> fout:
>     for line in fin:
>         fout.write(line[:-1] + ' 1.0\n')

Is that Python 3.x? I thought this "double context manager" could only be done 
with contextlib.nested, e.g.:
>>> with contextlib.nested(open(fn, "rb"), open(fn[:-4] + "_out.dat", "wb")) as 
>>> (r, w):
... for inline in r:
... w.write(inline + " " + "somevalue" + "\n")

Your code looks cleaner though.

Regards,
Albert-Jan
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Appending an extra column in a data file

2013-04-10 Thread eryksun
On Wed, Apr 10, 2013 at 4:45 PM, Albert-Jan Roskam  wrote:
>
>> with open('old.dat') as fin, open('new.dat', 'w') as fout:
>
> Is that Python 3.x?

It's the same syntax as an import statement such as the following:

import numpy as np, matplotlib as mpl

A downside with this is the inability to split long lines by adding
parentheses. Obviously you can break at the open() call:

with open('old.dat') as fin, open(
 'new.dat', 'w') as fout:
for line in fin:

But I think it's more readable to break up a long line like this:

fin = open('old.dat')
fout = open('new.dat', 'w')

with fin, fout:
for line in fin:
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Appending an extra column in a data file

2013-04-10 Thread Oscar Benjamin
On 10 April 2013 21:45, Albert-Jan Roskam  wrote:
>
>
>> Subject: Re: [Tutor] Appending an extra column in a data file
>>
> 
>
>> The file you attached is a space-delimited text file. If you want to
>> add a third column with the value '1.0' on every row you can just do:
>>
>> with open('old.dat') as fin, open('new.dat', 'w') as
>> fout:
>> for line in fin:
>> fout.write(line[:-1] + ' 1.0\n')
>
> Is that Python 3.x? I thought this "double context manager" could only be 
> done with contextlib.nested, e.g.:
 with contextlib.nested(open(fn, "rb"), open(fn[:-4] + "_out.dat", "wb")) 
 as (r, w):
> ... for inline in r:
> ... w.write(inline + " " + "somevalue" + "\n")

The contextlib.nested context manager does not work properly. The docs
http://docs.python.org/2/library/contextlib.html#contextlib.nested
say that it was deprecated in Python 2.7. To quote:

'''Deprecated since version 2.7: The with-statement now supports this
functionality directly (without the confusing error prone quirks).'''

The reason for its deprecation was that it cannot catch errors raised
during the function calls that create the underlying context managers.
This means that if the first open succeeds and the second fails (e.g.
because the file doesn't exist) then the with statement has no way of
guaranteeing that the first file gets closed.

Eryksun has pointed out the downside in relation to breaking long
lines. My preferred solution is just to literally nest the with
statements:

with open('old.dat'):
with open('new.dat', 'w'):
for line in fin:
fout.write(line[:-1] + ' 1.0\n')

If your use case is more complicated then Python 3.3 gives you the ExitStack:
http://docs.python.org/3.3/library/contextlib.html#contextlib.ExitStack


Oscar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Appending an extra column in a data file

2013-04-10 Thread Oscar Benjamin
On 10 April 2013 22:17, eryksun  wrote:
>
> But I think it's more readable to break up a long line like this:
>
> fin = open('old.dat')
> fout = open('new.dat', 'w')
>
> with fin, fout:
> for line in fin:

This has the same problems as contextlib.nested: An error raised while
opening 'new.dat' could prevent 'old.dat' from being closed properly.


Oscar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Appending an extra column in a data file

2013-04-10 Thread eryksun
On Wed, Apr 10, 2013 at 5:49 PM, Oscar Benjamin
 wrote:
>> fin = open('old.dat')
>> fout = open('new.dat', 'w')
>>
>> with fin, fout:
>> for line in fin:
>
> This has the same problems as contextlib.nested: An error raised while
> opening 'new.dat' could prevent 'old.dat' from being closed properly.

Thanks for pointing out the potential bug there. It's not a big
problem in this case with the file open for reading. But, yeah, I'm
hanging my head in shame here... ;)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python bz2 "IOError: invalid data stream" when trying to decompress

2013-04-10 Thread Rodney Lewis
My question is at StackOverflow so I won't repeat it here.

http://stackoverflow.com/questions/15938629/python-bz2-ioerror-invalid-data-stream-when-trying-to-decompress

Thanks so much in advance for any help you can provide regarding this.

http://www.squidoo.com/introductiontopython

-- 
Rodney Lewis
Please Visit My Homepage:
http://www.squidoo.com/dotcomboy
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python bz2 "IOError: invalid data stream" when trying to decompress

2013-04-10 Thread Dave Angel

On 04/10/2013 08:18 PM, Rodney Lewis wrote:

My question is at StackOverflow so I won't repeat it here.

http://stackoverflow.com/questions/15938629/python-bz2-ioerror-invalid-data-stream-when-trying-to-decompress

Thanks so much in advance for any help you can provide regarding this.

http://www.squidoo.com/introductiontopython




Works for me, after I turned the fragment into a program.  Python 2.7.3 
and Linux.


Perhaps you could be a bit more thorough in your problem description. 
Supply the whole program (40 lines isn't too big), and show the exact 
command line you used for both runs.  And show the full traceback, not 
just a summary.





--
DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Sharing Code Snippets

2013-04-10 Thread Amit Saha
Hello everyone,

I am not sure if this has been shared on this list. However, to help
both those seeking help and those wanting to help, may I suggest that
for all of you posting your programs, how about using a service such
as GitHub's Gists [1]. It allows you to post entire programs with
advantages such as intact code formatting, syntax highlighting and
perhaps others such as version control.

I hope that's a useful suggestion.

[1] https://gist.github.com/

Best,
Amit.

--
http://amitsaha.github.com/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python bz2 "IOError: invalid data stream" when trying to decompress

2013-04-10 Thread eryksun
On Wed, Apr 10, 2013 at 8:18 PM, Rodney Lewis
 wrote:
> My question is at StackOverflow so I won't repeat it here.

Short link:
http://stackoverflow.com/q/15938629/205580

Your function worked fine for me on Windows Python 2.7.3,
compressing/decompressing a text file that's about 150 KiB.

The bz2 module raises IOError("invalid data stream") for the error
codes BZ_DATA_ERROR and BZ_DATA_ERROR_MAGIC:

http://hg.python.org/cpython/file/70274d53c1dd/Modules/bz2module.c#l192

According to the bzip2 docs, BZ_DATA_ERROR is raised when the computed
CRC fails to match the stored CRC, or there's some other anomaly in
the data. BZ_DATA_ERROR_MAGIC means the compressed data didn't start
with the 'BZh' magic bytes.

http://www.bzip.org/1.0.5/bzip2-manual-1.0.5.html#err-handling
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Sharing Code Snippets

2013-04-10 Thread Sayan Chatterjee
Tried it out.It's really cool.From next time on, shall try to make use of
this. Thanks. :)


On 11 April 2013 06:58, Amit Saha  wrote:

> Hello everyone,
>
> I am not sure if this has been shared on this list. However, to help
> both those seeking help and those wanting to help, may I suggest that
> for all of you posting your programs, how about using a service such
> as GitHub's Gists [1]. It allows you to post entire programs with
> advantages such as intact code formatting, syntax highlighting and
> perhaps others such as version control.
>
> I hope that's a useful suggestion.
>
> [1] https://gist.github.com/
>
> Best,
> Amit.
>
> --
> http://amitsaha.github.com/
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 


--
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running python from windows command prompt

2013-04-10 Thread Arijit Ukil
Thanks for the help. Now I have modifed the code as:

import sys

def main(argv):

data = int(sys.argv[1])
 
avg = average (data)
 
print "Average:", avg

def average(num_list):
return sum(num_list)/len(num_list)

if __name__ == "__main__":
   main(sys.argv[1:])

When running in command line I am getting these errors:
In case 1. data = sys.argv[1]
In case 2, data = float(sys.argv[1])
In case 3, data = int (sys.argv[1])





Regards,
Arijit Ukil
Tata Consultancy Services
Mailto: arijit.u...@tcs.com
Website: http://www.tcs.com

Experience certainty.   IT Services
Business Solutions
Outsourcing




From:
Alan Gauld 
To:
tutor@python.org
Date:
04/10/2013 10:58 PM
Subject:
Re: [Tutor] Running python from windows command prompt
Sent by:
"Tutor" 



On 10/04/13 13:32, Arijit Ukil wrote:
> I like to run a python program "my_python.py" from windows command
> prompt. This program ( a function called testing) takes input as block
> data (say data = [1,2,3,4] and outputs processed single data.
>

Hopefully the code below is not your entire program. If it is it won't 
work. You define 2 functions but never call them.

Also you don't print anything so there is no visible output.
Finally this a code does not read the values from sys.argv.
(See my tutorial topic 'Talking to the user')

As for the error message, others have replied but basically you need
to either change to the folder that your file exists in or specify
the full path at the command prompt.

> import math
>
> def avrg(data):
> return sum(data)/len(data)
>
> def testing (data):
> val = avrg(data)
> out = pow(val,2)
> return out

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


=-=-=
Notice: The information contained in this e-mail
message and/or attachments to it may contain 
confidential or privileged information. If you are 
not the intended recipient, any dissemination, use, 
review, distribution, printing or copying of the 
information contained in this e-mail message 
and/or attachments to it are strictly prohibited. If 
you have received this communication in error, 
please notify us by reply e-mail or telephone and 
immediately and permanently delete the message 
and any attachments. Thank you


<>___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running python from windows command prompt

2013-04-10 Thread Asokan Pichai
On Thu, Apr 11, 2013 at 11:38 AM, Arijit Ukil  wrote:

> Thanks for the help. Now I have modifed the code as:
>
> import sys
>
> def main(argv):
>
> data = int(sys.argv[1])
>
> avg = average (data)
>
> print "Average:", avg
>
> def average(num_list):
> return sum(num_list)/len(num_list)
>
> if __name__ == "__main__":
>main(sys.argv[1:])
>


Two major problems:
One:
The __main__ methods processes (correctly) the args and drops argv[0]

But your main() function is calling sys.argv again

Two:
sum() and len() expect a list -- more accurately an iterable.
when you say
 data = argv[1]
data is a scalar.

If you know of list comprehensions, it can be easier or else,
think of a function to convert a list of strings (argv[1:] to a list
of floats; more general than int)


def arg2list(arg):
  args = []
  for a in arg:
   args.append(float(a))
  return args

Now replace the data = line with

data = arg2list(argv) # NOT sys.argv

HTH

Asokan Pichai

"Expecting the world to treat you fairly because you are a good person is a
little like expecting the bull to not attack you because you are a
vegetarian"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running python from windows command prompt

2013-04-10 Thread Alan Gauld

On 11/04/13 07:08, Arijit Ukil wrote:

Thanks for the help. Now I have modifed the code as:

import sys

def main(argv):
 data = int(sys.argv[1])
 avg = average (data)
 print "Average:", avg

def average(num_list):
 return sum(num_list)/len(num_list)

if __name__ == "__main__":
main(sys.argv[1:])

When running in command line I am getting these errors:
In case 1. data = sys.argv[1]
In case 2, data = float(sys.argv[1])
In case 3, data = int (sys.argv[1])


Try printing data to see what you are doing wrong in each case.
You need data to be a list of numbers. None of your three cases produces 
that.




--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor