[Tutor] conditional renaming folder and files in the tree

2017-08-12 Thread banda gunda
Dear Tutor,

I want to change the name of the folders and the files in the tree.
All those folders and files starting with name string '---'.
Examples:
If a  folder name is : \---DAT1
I want to change this to: \changedDAT1
If a file name is: \---1.txt
I want to change this to: \changed1.txt

I have attached the code and output to this email.
Specifically, I like to provide correct syntax (dst / destination) for line 6 
code block below!
I have not understood the syntax.

Thanks in advance, for your help .
best,
banda
+


for root, dirs, files in os.walk(".", topdown=False):
for name in files:
print(os.path.join(root, name))
os.rename(name.replace("---", "changed"))
list_of_files[name] = os.sep.join([dirpath, name])
print (list_of_files)

for name in dirs:
print(os.path.join(root, name))


.\---DAT1\---1.txt


---
TypeError Traceback (most recent call last)
 in ()
  2 for name in files:
  3 print(os.path.join(root, name))
> 4 os.rename(name.replace("---", "changed"))
  5 list_of_files[name] = os.sep.join([dirpath, name])
  6 print (list_of_files)

TypeError: Required argument 'dst' (pos 2) not found

_end_of_email

  In [1]:

 import os
 import sys
 import glob

  In [2]:

 print ("Current directory is %s: " %os.getcwd())

 Current directory is C:\Users\mysku\AnacondaProjects:

  In [3]:

 path = "E://"

 # Check current working directory.
 retval = os.getcwd()
 print ("Current working directory %s" % retval)

 # Now change the directory
 os.chdir( path )

 # Check current working directory.
 retval = os.getcwd()

 print ("Directory changed successfully %s" % retval)

 Current working directory C:\Users\mysku\AnacondaProjects
 Directory changed successfully E:\

  In [4]:

 # listing directories
 print ("The dir is: %s"%os.listdir(os.getcwd()))

 The dir is: ['---DAT1', '---DAT2']

  In [5]:

 for root, dirs, files in os.walk(".", topdown=False):
 for name in files:
 print(os.path.join(root, name))
 for name in dirs:
 print(os.path.join(root, name))

 .\---DAT1\---1.txt
 .\---DAT1\---2.txt
 .\---DAT1\---3.txt
 .\---DAT2\---5.txt
 .\---DAT2\---6.txt
 .\---DAT2\---7.txt
 .\---DAT1
 .\---DAT2

   this works for root folders

   for fileName in os.listdir("."): os.rename(fileName,
   fileName.replace("---", "changed"))

  In [6]:

 for root, dirs, files in os.walk(".", topdown=False):
 for name in files:
 print(os.path.join(root, name))
 os.rename(name.replace("---", "changed"))
 list_of_files[name] = os.sep.join([dirpath, name])
 print (list_of_files)

 for name in dirs:
 print(os.path.join(root, name))

 .\---DAT1\---1.txt

 ---
 TypeError Traceback (most recent call last)
  in ()
   2 for name in files:
   3 print(os.path.join(root, name))
 > 4 os.rename(name.replace("---", "changed"))
   5 list_of_files[name] = os.sep.join([dirpath, name])
   6 print (list_of_files)

 TypeError: Required argument 'dst' (pos 2) not found
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] conditional renaming folder and files in the tree

2017-08-12 Thread Alan Gauld via Tutor
On 11/08/17 16:10, banda gunda wrote:

> for root, dirs, files in os.walk(".", topdown=False):
> for name in files:
> print(os.path.join(root, name))
> os.rename(name.replace("---", "changed"))

Here you give the new name but not the original name.
The function needs two values, the source(original name)
and the destination(dst)


> list_of_files[name] = os.sep.join([dirpath, name])

What is dirpath? This is its first mention.

> ---
> TypeError Traceback (most recent call last)
>  in ()
> > 4 os.rename(name.replace("---", "changed"))
> 
> TypeError: Required argument 'dst' (pos 2) not found

See above

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] Percentage of installations without setuptools (Was if __name__=='__main__' ...)

2017-08-12 Thread Steven D'Aprano
On Fri, Aug 11, 2017 at 02:35:00PM +0200, Thomas Güttler wrote:

> How high is the percentage of python installation which don't have 
> setuptools?
> 
> I have no clue. Is it 5%, 10%, 15% ...?
> 
> I know there is no definite answer to this question. But you can guess this 
> better than me.

Somewhere between 0.1% and 99.9%.

For what little it is worth, out of the 9 versions of Python I have 
installed on my personal machines, setuptools is installed for 4 of 
them. On work machines, 2 out of 5 have setuptools installed. So in 
total, 6 out of 14 Python installations I have access to include 
setuptools. So 57% *don't* have setup tools.

Really Thomas, why do you care? If you want to require setuptools for 
your packages, go right ahead. If you want to tell people that using 
setuptools is the best choice, or the most popular choice, or the 
smartest choice, do so.

Just don't say it is the "default choice" because that is silly. The 
whole purpose of something being *default* is so that you DON'T have to 
make a choice. Obviously that doesn't apply to choosing a packaging 
library, and especially not to choosing a packaging language which may 
not even be present. Even if its only missing 1% of the time.

As a third-party author, the sorts of people who don't have setuptools 
installed either won't be installing your software at all, or will be 
installing it from source.


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


[Tutor] Long post: Request comments on starting code and test code on chess rating project.

2017-08-12 Thread boB Stepp
I mentioned in one of the recent threads that I started that it is
probably time for me to attempt a substantial project using the OO
paradigm.  I have had no coursework or training in OOP other than my
recent self-studies.  Everything (Other than toy practice examples.) I
have coded to date has been strictly procedural, similar to what I
learned in FORTRAN ages ago.  Also, I am continuing to try to do TDD
and keep things DRY.  So I am hoping for a thorough critique of what I
will shortly present.  Everything is fair game!  Hopefully my
self-esteem is up to this critique!

The intent of this project is more than just calculate chess ratings.
I also envision being able to store a record of all game results and
player information for my school chess players that I give lessons to.
Some functionality I will strive to include:  1) Be able to re-rate
all games from a given date to the present.  2) Record demographic
information about my players, such as names, current school year,
current grade, etc.  3) Have a very friendly GUI so that when I have a
finished project, a student could easily take over responsibility of
maintaining the school's player ratings, if I so choose to allow this.
4) Having an editor where games and player data (But NOT ratings;
these would have to be re-rated starting from a corrected game(s).)
can be edited, inserted, or deleted with games (If game data is
edited.) automatically be re-rated.  5) Et cetera ...

My current project structure is:

/Projects
/rating_calculator
/rating_calculator
__init__.py
main.py
/tests
__init__.py
test_main.py

I have started my coding with a RatingCalculator class.  The intent of
this class is to gather all methods together needed to validate and
calculate chess ratings.  My intent is to only ever have a single
instance of this class existing during a given running of the program.
(BTW, is there a technique to _guarantee_ that this is always true?)
I am only at the very beginning of coding this class.  I have not
added any methods yet.  Currently I am adding class constants that
will be used in this class' methods.  These constants are for internal
class use only and should not be altered from outside the class.  Here
is the current state of the main.py program (Which will probably be
broken into multiple modules as the project develops.):

=
#!/usr/bin/env python3

"""Module to process chess ratings."""

class RatingCalculator:
"""This class contains methods to validate and calculate chess ratings."""

# Overestimated extremes for possible chess rating values.  Values outside
# this range should not be achievable.

_LOWEST_POSSIBLE_RATING = 0
_HIGHEST_POSSIBLE_RATING = 3000

# Fundamental constants for use in the chess rating formula.  The keys to
# these values are tuples giving the rating ranges for which these
# K-factors are valid.

_K_MULTIPLIERS = {
(_LOWEST_POSSIBLE_RATING, 2099): 0.04,
(2100, 2399): 0.03,
(2400, _HIGHEST_POSSIBLE_RATING): 0.02}

_K_ADDERS = {
(_LOWEST_POSSIBLE_RATING, 2099): 16,
(2100, 2399): 12,
(2400, _HIGHEST_POSSIBLE_RATING): 8}
=

The test code in test_main.py is:

=
#!/usr/bin/env python3

"""Module to test all functions and methods of main.py."""

import unittest
import rating_calculator.main as main

class TestRatingCalculatorConstants(unittest.TestCase):
# Check that the constants in RatingCalculator have the proper values.

def setUp(self):
# Create instance of RatingCalculator for use in the following tests.
# Create tuple of test-value pairs to interate over in subtests.

self.rating_calculator = main.RatingCalculator()
self.test_value_pairs = (
(self.rating_calculator._LOWEST_POSSIBLE_RATING, 0),
(self.rating_calculator._HIGHEST_POSSIBLE_RATING, 3000),
(self.rating_calculator._K_MULTIPLIERS[(
self.rating_calculator._LOWEST_POSSIBLE_RATING, 2099)],
0.04),
(self.rating_calculator._K_MULTIPLIERS[(2100, 2399)], 0.03),
(self.rating_calculator._K_MULTIPLIERS[(2400,
self.rating_calculator._HIGHEST_POSSIBLE_RATING)], 0.02),
(self.rating_calculator._K_ADDERS[(
self.rating_calculator._LOWEST_POSSIBLE_RATING, 2099)],
16),
(self.rating_calculator._K_ADDERS[(2100, 2399)], 12),
(self.rating_calculator._K_ADDERS[(2400,
self.rating_calculator._HIGHEST_POSSIBLE_RATING)], 8))


def test_class_constants(self):
# Check that all 

Re: [Tutor] Long post: Request comments on starting code and test code on chess rating project.

2017-08-12 Thread Steven D'Aprano
I haven't had a chance to read the entire post in detail, but one thing 
which stands out:

On Sun, Aug 13, 2017 at 12:22:52AM -0500, boB Stepp wrote:

> I have started my coding with a RatingCalculator class.  The intent of
> this class is to gather all methods together needed to validate and
> calculate chess ratings.  My intent is to only ever have a single
> instance of this class existing during a given running of the program.
> (BTW, is there a technique to _guarantee_ that this is always true?)

Yes, this is called the "Singleton" design pattern, which is very 
possibly the most popular and common design pattern in OOP.

It is also very possibly the *least appropriate* use of OOP techniques 
imaginable, so much so that many people consider it to be an 
anti-pattern to be avoided:

https://www.michaelsafyan.com/tech/design/patterns/singleton

(follow the links at the bottom of the page for more information about 
why singletons are considered harmful).

It is popular because:

- it is easy to understand;

- it is easy to program, at least in languages like Java and C++ 
  (less so in Python);

- consequently it is often the first OOP design patterns taught;

- and it makes up for a deficiency in Java, or at least the Java
  philosophy, namely the lack or avoidance of top-level functions.

http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html

In Python, the equivalent to the singleton is the module. If you have a 
class full of methods which is only ever going to be instantiated once, 
*almost always* the solution in Python is to use a module full of 
functions.

There are few exceptions, but they're generally identity-objects only, 
with little or no state and few if any methods:

- None
- NotImplemented
- Ellipsis
- True and False (okay, duotons not singletons)

I can't think of any other obvious examples.

By "identity-object", I mean an object whose value is synonymous with 
its identity, rather than two separate aspects of the object.

With regular objects, their value is independent of their identity. 
Their identity is "which particular object is this?" while their value 
is separate: you can easily have you have two floats with same value 
(say, both 1.25) without them necessarily being the same object. 
Likewise we can have two distinct lists which happen to have the same 
value: they both have the value [1, 2, 3], but they're different lists 
with the same value rather than the same list.

With regular objects, just because they have the same value doesn't 
necessarily mean they must be the same object, they may be distinct 
objects with the same value.

But the value of None is not separate from its identity. None has no 
value *except the fact that it is the None object*. Its value is not 
separate from its identity, its value is its identity.

So, coming back to your RatingCalculator class:

(1) Can you think of any possible circumstances where you might want two 
distinct RatingCalculators at the same time? Could you not have two 
different calculation methods? If so, then use a class, but allow it to 
be instantiated as often as you need.

(2) If there is absolutely no possible reason to want two such 
calculators, then there is little reason to use a class at all. 
Singletons are just global-level state disguised as an object.


A third option:

Look at the source code for the random module. It has a Random class, so 
that you can have as many different, *independent* random number 
generators as you need. They can be subclassed to use different 
mechanisms for generating pseudo-random numbers, or they can use the 
same algorithm but be in different internal states.

But since *most* people don't need more than one RNG at a time, there's 
also a hidden instance, pre-instantiated when the module is imported for 
the first time, which is used to provide module-level RNG functions. The 
caller doesn't need to know that under the hood there's a private 
instance. Advanced users can create their own instances, while simple 
cases just call the module-level functions.



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