id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
19,200 | pytest testing framework setting up pytest you will probably need to set up pytest so that you can use it from within your environment if you are using the pycharm editorthen you will need to add the pytest module to the current pycharm project and tell pycharm that you want to use pytest to run all tests for you simple pytest example something to test to be able to explore pytest we first need something to testwe will therefore define simple calculator class the calculator keeps running total of the operations performedit allows new value to be set and then this value can be added toor subtracted fromthat accumulated total class calculatordef __init__(self)self current self total def set(selfvalue)self current value def add(self)self total +self current def sub(self)self total -self current def total(self)return self total save this class into file called calculator py writing test we will now create very simple pytest unit test for our calculator class this test will be defined in class called test_calculator py you will need to import the calculator class we wrote above into your test_calculator py file (remember each file is module in python |
19,201 | simple pytest example the exact import statement will depend on where you placed the calculator file relative to the test class in this case the two files are both in the same directory and so we can writefrom calculator import calculator we will now define testthe test should be pre-fixed with test_ for pytest to find them in fact pytest uses several conventions to find testswhich aresearch for test_py or *_test py files from those filescollect test itemstest_prefixed test functionstest_prefixed test methods inside test prefixed test classes (without an__init__methodnote that we keep test files and the files containing the code to be tested separateindeed in many cases they are kept in different directory structures this means that there is not chance of developers accidentally using tests in production code etc now we will add to the file function that defines test we will call the function test_add_oneit needs to start with test_ due to the above convention howeverwe have tried to make the rest of the function name descriptiveso that its clear what it is testing the function definition is given belowfrom calculator import calculator def test_add_one()calc calculator(calc set( calc add(assert calc total = the test function creates new instance of the calculator class and then calls several methods on itto set up the value to addthen the call to the add(method itself etc the final part of the test is the assertion the assert verifies that the behaviour of the calculator is as expected the pytest assert statement works out what is being tested and what it should do with the result--including adding information to be added to test run report it avoids the need to have to learn load of assertsomething type methods (unlike some other testing frameworksnote that test without an assertion is not testi it does not test anything many ides provide direct support for testing frameworks including pycharm for examplepycharm will now detect that you have written function with an assert statement in it and add run test icon to the grey area to the left of the |
19,202 | pytest testing framework editor this can be seen in the following picture where green arrow has been added at line this is the 'run testbuttonthe developer can click on the green arrow to run the test they will then be presented with the run menu that is preconfigured to use pytest for youif the developer now selects the run optionthis will use the pytest runner to execute the test and collect information about what happened and present it in pytest output view at the bottom of the idehere you can see tree in the left-hand panel that currently holds the one test defined in the test_calculator py file this tree shows whether tests have passed or failed in this case we have green tick showing that the test passed to the right of this tree is the main output panel which shows the results of running the tests in this case it shows that pytest ran only one test and that this was the test_add_one test which was defined in test_calculator py and that test passed if you now change the assertion in the test to check to see that the result is the test will fail when runthe ide display will update accordingly the tree in the left-hand pane now shows the test as failed while the right-hand pane provides detailed information about the test that failed including where in the test the failed assertion was defined this is very helpful when trying to debug test failures |
19,203 | working with pytest working with pytest testing functions we can test standalone functions as well as classes using pytest for examplegiven the function increment below (which merely adds one to any number passed into it)def increment( )return we can write pytest test for this as followsdef test_increment_integer_ ()assert increment( = the only real difference is that we have not had to make an instance of classorganising tests tests can be grouped together into one or more filespytest will search for all files following the naming convention (file names that either start or end with 'test'in specified locationsif no arguments are specified when pytest is run then the search for suitably named test files starts from the testpaths environment variable (if configuredor the current directory alternativelycommand line arguments can be used in any combination of directories or filenames etc |
19,204 | pytest testing framework pytest will recursively search down into sub directoriesunless they match norecursedirs environment variable in those directoriesit will search for files that match the naming conventions test_py or *_test py files tests can also be arranged within test files into test classes using test classes can be helpful in grouping tests together and managing the setup and tear down behaviours of separate groups of tests howeverthe same effect can be achieved by separating the tests relating to different functions or classes into different files test fixtures it is not uncommon to need to run some behaviour before or after each test or indeed before or after group of tests such behaviours are defined within what is commonly known as test fixtures we can add specific code to runat the beginning and end of test class module of test code (setup_moduleteardown_moduleat the beginning and end of test class (setup_class/teardown_classor using the alternate style of the class level fixtures (setup/teardownbefore and after test function call (setup_function/teardown_functionbefore and after test method call (setup_method/teardown_methodto illustrate why we might use fixturelet us expand our calculator testdef test_initial_value()calc calculator(assert calc total = def test_add_one()calc calculator(calc set( calc add(assert calc total = def test_subtract_one()calc calculator(calc set( calc sub(assert calc total =- def test_add_one_and_one()calc calculator(calc set( calc add(calc set( calc add(assert calc total = |
19,205 | working with pytest we now have four tests to run (we could go further but this is enough for nowone of the issues with this set of tests is that we have repeated the creation of the calculator object at the start of each test while this is not problem in itself it does result in duplicated code and the possibility of future issues in terms of maintenance if we want to change the way calculator is created it may also not be as efficient as reusing the calculator object for each test we can howeverdefine fixture that can be run before each individual test function is executed to do this we will write new function and use the pytest fixture decorator on that function this marks the function as being special and that it can be used as fixture on an individual function functions that require the fixture should accept reference to the fixture as an argument to the individual test function for examplefor test to accept fixture called calculatorit should have an argument with the fixture namei calculator this name can then be used to access the object returned this is illustrated belowimport pytest from calculator import calculator @pytest fixture def calculator()"""returns calculator instance""return calculator(def test_initial_value(calculator)assert calculator total = def test_add_one(calculator)calculator set( calculator add(assert calculator total = def test_subtract_one(calculator)calculator set( calculator sub(assert calculator total =- def test_add_one_and_one(calculator)calculator set( calculator add(calculator set( calculator add(assert calculator total = |
19,206 | pytest testing framework in the above codeeach of the test functions accepts the calculator fixture that is used to instantiate the calculator object we have therefore de-duplicated our codethere is now only one piece of code that defines how calculator object should be created for our tests note each test is supplied with completely new instance of the calculator objectthere is therefore no chance of one test impacting on another test it is also considered good practice to add docstring to your fixtures as we have done above this is because pytest can produce list of all fixtures available along with their docstrings from the command line this is done usingpytest fixtures the pytest fixtures can be applied to functions (as above)classesmodulespackages or sessions the scope of fixture can be indicated via the (optionalscope parameter to the fixture decorator the default is "functionwhich is why we did not need to specify anything above the scope determines at what point fixture should be run for examplea fixture with 'sessionscope will be run once for the test sessiona fixture with module scope will be run once for the module (that is the fixture and anything it generates will be shared across all tests in the current module) fixture with class scope indicates fixture that is run for each new instance of test class created etc another parameter to the fixture decorator is autouse which if set to true will activate the fixture for all tests that can see it if it is set to false (which is the defaultthen an explicit reference in test function (or method etc is required to activate the fixture if we add some additional fixtures to our tests we can see when they are runimport pytest from calculator import calculator @pytest fixture(scope='session'autouse=truedef session_scope_fixture()print('session_scope_fixture'@pytest fixture(scope='module'autouse=truedef module_scope_fixture()print('module_scope_fixture'@pytest fixture(scope='class'autouse=truedef class_scope_fixture()print('class_scope_fixture'@pytest fixture def calculator()"""returns calculator instance""print('calculator fixture'return calculator( |
19,207 | working with pytest def test_initial_value(calculator)assert calculator total = def test_add_one(calculator)calculator set( calculator add(assert calculator total = def test_subtract_one(calculator)calculator set( calculator sub(assert calculator total =- def test_add_one_and_one(calculator)calculator set( calculator add(calculator set( calculator add(assert calculator total = if we run this version of the teststhen the output shows when the various fixtures are runsession_scope_fixture module_scope_fixture class_scope_fixture calculator fixture class_scope_fixture calculator fixture class_scope_fixture calculator fixture class_scope_fixture calculator fixture note that higher scoped fixtures are instantiated first parameterised tests one common requirement of test to run the same tests multiple times with several different input values this can greatly reduce the number of tests that must be defined such tests are referred to as parametrised testswith the parameter values for the test specified using the @pytest mark parametrize decorator |
19,208 | pytest testing framework @pytest mark parametrize decorator @pytest mark parametrize('input ,input ,expected'( )( )]def test_calculator_add_operation(calculatorinput input ,expected)calculator set(input calculator add(calculator set(input calculator add(assert calculator total =expected this illustrates setting up parametrised test for the calculator in which two input values are added together and compared with the expected result note that the parameters are named in the decorator and then list of tuples is used to define the values to be used for the parameters in this case the test_ calculator_add_operation will be run two passing in and and then passing in and for the parameters input input and expected respectively testing for exceptions you can write tests that verify that an exception was raised this is useful as testing negative behaviour is as important as testing positive behaviour for examplewe might want to verify that particular exception is raised when we attempt to withdraw money from bank account which will take us over our overdraft limit to verify the presence of an exception in pytest use the with statement and pytest raises this is context manager that will verify on exit that the specified exception was raised it is used as followswith pytest raises(accounts balanceerror)current_account withdraw( ignoring tests in some cases it is useful to write test for functionality that has not yet been implementedthis may be to ensure that the test is not forgotten or because it helps to document what the item under test should do howeverif the test is run then the test suite as whole will fail because the test is running against behaviour that has yet to be written |
19,209 | parameterised tests one way to address this problem is to decorate test with the @pytest mark skip decorator@pytest mark skip(reason='not implemented yet'def test_calculator_multiply(calculator)calculator multiply( assert calculator total = this indicates that pytest should record the presence of the test but should not try to execute it pytest will then note that the test was skippedfor example in pycharm this is shown using circle with line through it it is generally considered best practice to provide reason why the test has been skipped so that it is easier to track this information is also available when pytest skips the test online resources see the following online resources for information on pytestintroduction pytest exercises create simple calculator class that can be used for testing purposes this simple calculator can be used to addsubtractmultiple and divide numbers |
19,210 | pytest testing framework this will be purely command driven application that will allow the user to specify the operation to perform and the two numbers to use with that operation the calculator object will then return result the same object can be used to repeat this sequence of steps this general behaviour of the calculator is illustrated below in flow chart formyou should also provide memory function that allows the current result to be added to or subtracted from the current memory total it should also be possible to retrieve the value in memory and clear the memory next write pytest set of tests for the calculator class think about what tests you need to writeremember you can' write tests for every value that might be used for an operationbut consider the boundaries - - + etc of course you also need to consider the cumulative effect of the behaviour of the memory feature of the calculatorthat is multiple memory adds or memory subtractions and combinations of these as you identify tests you may find that you have to update your implementation of the calculator class have you taken into account all input optionsfor example dividing by zero--what should happen in these situations |
19,211 | mocking for testing introduction testing software systems is not an easy thing to dothe functionsobjectsmethods etc that are involved in any program can be complex things in their own right in many cases they depend on and interact with other functionsmethods and objectsvery few functions and methods operate in isolation thus the success of failure of function or method or the overall state of an object is dependent on other program elements howeverin general it is lot easier to test single unit in isolation rather than to test it as part of larger more complex system for examplelet us take python class as single unit to be tested if we can test this class on its own we only have to take into account the state of the classes object and the behaviour defined for the class when writing our test and determining appropriate outcomes howeverif that class interacts with external systems such as external servicesdatabasesthird party softwaredata sources etc then the testing process becomes more complex(cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science |
19,212 | mocking for testing it may now be necessary to verify data updates made to the databaseor information sent to remote service etc to confirm that the operation of class' object is correct this makes not only the software being tested more complex but it also makes the tests themselves more complex this means that there is greater chance that the test will failthat the tests will contain bugs or issues themselves and that the test will be harder for someone to understand and maintain thus common objective when writing unit tests or subsystem tests is to be able to test elementsunits in isolation the question is how to do this when function or method relies on other elementsthe key to decoupling functionsmethods and objects from other program or system elements is to use mocks these mocks can be used to decouple one object rom anotherone function from another and one system from anotherthereby simplifying the testing environment these mocks are only intended to be used for testing purposesfor example the above scenario could be simplified by mocking out each of the external systems as shown belowmocking is not python specific concept and there are many mocking libraries available for may different languages howeverin this we will be focussing on the unites mock library which has been part of the standard python distribution since python why mocka useful first question to consider with regard to mockingin software testingis 'why mock?that iswhy bother with the concept of mock in the first placewhy not test with the real thingthere are several answers to thissome of which are discussed below |
19,213 | why mock testing in isolation is easier as mentioned in the introductiontesting unit (whether that is classa functiona module etc is easier in isolation then when dependent on external classesfunctionsmodules etc the real thing is not available in many cases it is necessary to mock out part of system or an interface to another system because the real thing is just not available this could be for several reasons including that it has not been developed yet in the natural course of software development some parts of system are likely to be developed and ready for testing before other parts if one part relies on another part for some element of its operation then the system that is not yet available can be mocked out in other situations the development team or test team may not have access to the real thing this may because it is only available within production context for exampleif software development house is developing one subsystem it may not have access to another subsystem as it is proprietary and only accessible once the software has been deployed within the client organisation real elements can be time consuming we want our tests to run as quickly as possible and certainly within continuous integration (cienvironment we want them to run fast enough that we can repeatedly test system throughout the day in some situations the real thing may take significant amount of time to process the test scenario as we want to test our own code we may not be worried about whether system outside of our control operates correctly or not (at least at this level of testingit may still be concern for integration and system testingwe can therefore improve the response times of our tests if we mock out the real system and replace it with mock that provides much faster response times (possibly because it uses canned responsesthe real thing takes time to set up in continuous integration (cienvironmentnew builds of system are regularly and repeatedly tested (for example whenever change is made to their codebasein such situations it may be necessary to configure and deploy the final system to suitable environment to perform appropriate tests if an external system is time consuming to configuredeploy and initialise it may be more effective to mock that system out difficult to emulate certain situations it can be difficult within test scenario to emulate specific situations these situations are often related to error or exceptional circumstances that should never happen within correctly functioning environment howeverit may well be necessary to validate that if such situation does occurthen the software can deal with that scenario if these scanners are related to how external (the unit under testsystem fail or operate incorrectly then it may be necessary to mock out these systems to be able to generate the scenarios we want repeatable tests by their very nature when you run test you either want it to pass or fail each time it is run with the same inputs you certainly do not want tests that pass sometimes and fail other times this mean that there is no confidence in the tests and people often start ignoring failed tests this situation can |
19,214 | mocking for testing happen if the data provided by systems that test depends on do not supply repeatable data this can happen for several different reason but common cause is because they return real data such real data may be subject to changefor example consider system that uses data feed for the current exchange rate between funds and dollars if the associated test confirms that trade when priced in dollars is correctly converted to funds using the current exchange rate then that test is likely to generate different result every time it is run in this situation it would lie better to mock out the current exchange rate service so that fixed/known exchange rate is used the real system is not reliable enough in some cases the real system may not be reliable enough itself to allow for repeatable tests the real system may not allow tests to be repeated finallythe real system may not allow tests to be easily repeated for examplea test which involves lodging trade for certain number of ibm shares with an trade order management system may not allow that tradewith those sharesfor that customer to be run several times (as it would then appear to be multiple tradeshoweverfor the purposes of testing we may want to test submitting such trade in multipel different scenariosmultiple times it may therefore be necessary to mock out the real order management system so that such tests can be written what is mockingthe previous section gave several reasons to use mocksthe next thing to consider then is what is mockmocksincluding mock functionsmethods and mock objects are things thatpossess the same interface as the real thingwhether they are mock functionsmethods or whole objects they thus take the same range and types of parameters and return similar information using similar types define behaviour that in some way represents/mimics real exemplar behaviour but typically in very controlled ways this behaviour may be hard coedmay really on set of rules or simplified behaviourmay be very simplistic or quiet sophisticated in its own right they thus emulate the real system and from outside of the mock may actually appear to be the real system in many cases the term mock is used to cover range of different ways in which the real thing can be emulatedeach type of mock has its own characteristics it is therefore useful to distinguish the different types of mocks as this can help determine the style of mock to be adopted in particular test situation |
19,215 | what is mocking the are different types of mock includingtest stubs test stub is typically hand coded functionmethod or object used for testing purposes the behaviour implemented by test stub may represent limited sub set of the functionality of the real thing fakes fakes typically provide addition functionality compared with test stub fakes may be considered to be test specific version of the real thingsuch as an in memory database used for testing rather than the real database such fakes typically still have some limitations on their functionalityfor example when the tests are terminated all data is purged from the in memory database rather than stored permanently on disk autogenerated test mocks these are typically generated automatically using supporting framework as part of the set up of the test the expectations associated with the test mock these expectations may specify the results to return for specific inputs as well as whether the test mock was called etc test mock spy if we are testing particular unit and it returns the correct result we might decided that we do not need to consider the internal behaviour of the unit howeverit is common to want to confirm that the test mock was invoked in the ay we expected this helps verify the internal behaviour of the unit under test this can be done using test mock spy such test mock records how many times it was called and what the parameters used where (as well as other informationthe test can then interrogate the test mock to validate that it was invoked as expected/as many times as expected/with the correct parameters etc common mocking framework concepts as has been mentioned there are several mocking frameworks around for not only python but other languages such as javacand scala etc all of these frameworks have common core behaviour this behaviour allows mock functionmethod or object to be created based on the interface presented by the real thing of course unlike languages such as cand java python does not have formal interface concepthowever this does not stop the mocking framework from still using the same idea in general once mock has been created it is possible to define how that mock should appear to behavein general this involves specifying the return result to use for function or method it is also possible to verify that the mock has been invoked as expected with the parameters expected the actual mock can be added to test or set of tests either programmatically or via some form of decorator in either case for the duration of the test the mock will be used instead of the real thing |
19,216 | mocking for testing assertions can then be used to verify the results returned by the unit under test while mock specific methods are typically used to verify (spy onthe methods defined on the mock mocking frameworks for python due to python' dynamic nature it is well suited to the construction of mock functionsmethods and objects in fact there are several widely used mocking frameworks available for python includingunittest mock the unittest mock (included in the python distribution from python onwardsthis is the default mocking library provided with python for creating mock objects in python tests pymox this is widely used making framework it is an open source framework and has more complete set of facilities for enforcing the interface of mocked class mocktest this is another popular mocking framework it has its own dsl (domain specific languageto support mocking and wide set of expectation matching behaviour for mock objects in the remainder of this we will focus on the unittest mock library as it is provided as part of the standard python distribution the unittest mock library the standard python mocking library is the unittest mock library it has been included in the standard python distribution since python and provides simple way to define mocks for unit tests the key to the unittest mock library is the mock class and its subclass magicmock mock and magicmock objects can be used to mock functionsmethods and even whole classes these mock objects can have canned responses defined so that when they are involved by the unit under test they will respond appropriately existing objects can also have attributes or individual methods mocked allowing an object to be tested with known state and specified behaviour to make it easy to work with mock objectsthe library provides the @unittest mock patch(decorator this decorator can be used to replace real functions and objects with mock instances the function behind the decorator can also be used as context manager allowing it to be used in with-as statements providing for fine grained control over the scope of the mock if required |
19,217 | the unittest mock library mock and magic mock classes the unittest mock library provides the mock class and the magicmock class the mock class is the base class for mock objects the magicmock class is subclass of the mock class it is called the magicmock class as it provides default implementations for several magic method such as __len__()__str__()and __iter__(as simple example consider the following class to be testedclass someclass()def _hidden_method(self)return def public_method(selfx)return self hidden_method( this class defines two methodsone is intended as part of the public interface of the class (the public_method()and one it intended only for internal or private use (the _hidden_method()notice that the hidden method uses the convention of preceding its name by an underbar (' 'let us assume that we wish to test the behaviour of the public_method(and want to mock out the _hidden_method(we can do this by writing test that will create mock object and use this in place of the real _hidden_method(we could probably use either the mock class or the magicmock class for thishowever due to the additional functionality provided by the magicmock class it is common practice to use that class we will therefore do the same the test to be created will be defined within method within test class the names of the test method and the test class are by convention descriptive and thus will describe what is being testedfor examplefrom unittest mock import from unittest import testcase from unittest import main class test_someclass_public_interface(testcase)def test_public_method(self)test_object someclass(set up canned response on mock method test_object _hidden_method magicmock(name 'hidden_method'test_object _hidden_method return_value test the object result test_object public_method( self assertequal( result'return value from public_method incorrect' |
19,218 | mocking for testing in this case note that the class being tested is instantiated first the magicmock is then instantiated and assigned to the name of the method to be mocked this in effect replaces that method for the test_object the magicmock the magicmock object is given name as this helps with treating any issues in the report generated by the unites framework following this the canned response from the mock version of the _hidden_method(is definedit will always return the value at this point we have set up the mock to be used for the test and are now ready to run the test this is done in the next line where the public_method(is called on the test_object with the parameter the result is then stored the test then validates the result to ensure that it is correcti that the returned value is although this is very simple example it illustrates how method can be mocked out using the magicmock class the patchers the unittest mock patch()unittest mock patch object(and unittest patch dict(decorators can be used to simplify the creation of mock objects the patch decorator takes target for the patch and returns magicmock object in its place it can be used as tastcase method or class decorator as class decorator it decorates each test method in the class automatically it can also be used as context manager via the with and with-as statements the patch object decorator can be provided with either two or three arguments when given three arguments it will replace the object to be patchedwith mock for the given attribute/method name when given two arguments the object to be patched is given default magicmock object for the specified attribute/function the patch dict decorator patches dictionary or dictionary like object for examplewe can rewrite the example presented in the previous section using the @patch object decorator to provides the mock object for the _hidden_method((it returns magicmock linked to someclass) |
19,219 | the unittest mock library class test_someclass_public_interface(testcase)@patch object(someclass'_hidden_method'def test_public_method(selfmock_method)set up canned response mock_method return_value create object to be tested test_object someclass(result test_object public_method( self assertequal( result'return value from public_method incorrect'in the above code the _hidden_method(is replaced with mock version for someclass within the test_public_method(method note that the mock version of the method is passed in as parameter to the test method so that the canned response can be specified you can also use the @patch(decorator to mock function from module for examplegiven some external module with function api_callwe can mock that function out using the @patch(decorator@patch('external_module api_call'def test_some_func(selfmock_api_call)this uses patch(as decorator and passed the target object' path the target path was 'external_module api_callwhich consists of the module name and the function to mock mocking returned objects in the examples looked at so far the results returned from the mock functions or methods have been simple integers howeverin some cases the returned values must themselves be mocked as the real system would return complex object with multiple attributes and methods the following example uses magicmock object to represent an object returned from mocked function this object has two attributesone is response code and the other is json string json stands for the javascript object notation and is commonly used format in web services |
19,220 | mocking for testing import external_module from unittest mock import from unittest import testcase from unittest import main import json def some_func()calls out to external api which we want to mock response external_module api_call(return responseclass test_some_func_calling_api(testcase)class test_some_func_calling_api(testcase)@patch('external_module api_call'def test_some_func(selfmock_api_call)sets up mock version of api_call mock_api_call return_value magicmock(status_code= response=json dumps({'key':'value'})calls some_func(that calls the (mockapi_call(function result some_func(check that the result returned from some_func(is what was expected self assertequal(result status_code "returned status code is not "self assertequal(result response'{"key""value"}'"response json incorrect"in this example the function being tested is some_func(but some_func(calls out to the mocked function external_module api_call(this mocked function returns magicmock object with pre-specified status_code and response the assertions then validate that the object returned by some_func(contains the correct status code and response validating mocks have been called using unittest mock it is possible to validate that mocked function or method was called appropriately using assert_called()assert_called_with(or assert_called_once_with(depending on whether the function takes parameters or not |
19,221 | the unittest mock library the following version of the test_some_func_with_params(test method verifies that the mock api_call(function was called with the correct parameter @patch('external_module api_call_with_param'def test_some_func_with_param(selfmock_api_call)sets up mock version of api_call mock_api_call return_value magicmock(status_code= response=json dumps({'age'' '})result some_func_with_param('phoebe'check result returned from some_func(is what was expected self assertequal(result response'{age"" "}''json result incorrect'verify that the mock_api_call was called with the correct params mock_api_call api_call_with_param assert_called_with('phoebe'if we wished to validate that it had only been called once we could use the assert_called_once_with(method mock and magicmock usage naming your mocks it can be useful to give your mocks name the name is used when the mock appears in test failure messages the name is also propagated to attributes or methods of the mockmock magicmock(name='foo'mock classes as well as mocking an individual method on class it is possible to mock whole class this is done by providing the patch(decorator with the name of the class to patch (with no named attribute/methodin this case the while class is replaced by magicmock object you must then specify how that class should behave |
19,222 | mocking for testing import people from unittest mock import from unittest import testcase from unittest import main class mytest(testcase)@patch('people person'def test_one(selfmockperson)self assertis(people personmockpersoninstance mockperson return_value instance calculate_pay return_value payroll people payroll(result payroll generate_payslip(instanceself assertequal('you earned 'result'payslip incorrect'in this example the people person class has been mocked out this class has method calculate_pay(which is being mocked here the payroll class has method generate_payslip(that expects to be given person object it then uses the information provided by the person objects calculate_pay(method to generate the string returned by the generate_payslip(method attributes on mock classes attributes on mock object can be easily definedfor example if we want to set an attribute on mock object then we can just assign value to the attributeimport people from unittest mock import from unittest import testcase class mytest(testcase)@patch('people person'def test_one(selfmockperson)self assertis(people personmockpersoninstance mockperson return_value instance age instance name 'adamself assertequal( instance age'age incorrect'self assertequal('adam'instance name'name incorrect'in this case the attribute age and name have been added to the mock instance of the people person class |
19,223 | mock and magicmock usage if the attribute itself needs to be mock object then all that is required is to assign magicmock (or mockobject to that attributeinstance address magicmock(name='address'mocking constants it is very easy to mock out constantthis can be done using the @patch(decorator and proving the name of the constant and the new value to use this value can be literal value such as or 'helloor it can be mock object itself (such as magicmock objectfor example@patch('mymodule max_count' def test_something(self)test can now use mymodule max_count mocking properties it is also possible to mock python properties this is done again using the @patch decorator but using the unittest mock propertymock class and the new_callable parameter for example@patch('mymoule car wheels'new_callable=mock propertymockdef test_some_property(selfmock_wheels)mock_wheels return_value rest of test method raising exceptions with mocks very useful attribute that can be specified when mock object is created is the side_effect if you set this to an exception class or instance then the exception will be raised when the mock is calledfor examplemock mock(side_effect=exception('boom!')mock(this will result in the exception being raised when the mock(is invoked |
19,224 | mocking for testing applying patch to every test method if you want to mock out something for every test in test class then you can decorate the whole class rather than each individual method the effect of decorating the class is that the patch will be automatically applied to all test methods in the class ( to all methods starting with the word 'test'for exampleimport people from unittest mock import from unittest import testcase from unittest import main @patch('people person'class mytest(testcase)def test_one(selfmockperson)self assertis(people personmockpersondef test_two(selfmocksomeclass)self assertis(people personmocksomeclassdef do_something(self)return 'somethingin the above test classthe tests test_one and test_two are supplied with the mock version of the person class however the do_something(method is not affected using patch as context manager the patch function can be used as context manager this gives fine grained control over the scope of the mock object in the following example the the test_one(method contains with-as statement that we used to patch (mockthe person class as mockperson this mock class is only available within the with-as statement |
19,225 | mock and magicmock usage import people from unittest mock import from unittest import testcase from unittest import main class mytest(testcase)def test_one(self)with patch('people person'as mockpersonself assertis(people personmockpersoninstance mockperson return_value instance calculate_pay return_value payroll people payroll(result payroll generate_payslip(instanceself assertequal('you earned 'result'payslip incorrect' mock where you use it the most common error made by people using the unittest mock library is mocking in the wrong place the rule is that you must mock out where you are going to use itor to put it another way you must always mock the real thing where it is imported intonot where it' imported from patch order issues it is possible to have multiple patch decorators on test method howeverthe order in which you define the patch decorators is significant the key to understanding what the order should be is to work backwards so that when the mocks are passed into the test method they are presented to the right parameters for example@patch('mymodule sys'@patch('mymodule os'@patch('mymodule os path'def test_something(selfmock_os_pathmock_osmock_sys)the rest of the test method |
19,226 | mocking for testing notice that the last patch' mock is passed into the second parameter passed to the test_something(method (self is the first parameter to all methodsin turn the first patch' mock is passed into the last parameter thus the mocks are passed into the test method in the reverse order to that which they are defined in how many mocksan interesting question to consider is how many mocks should you use per testthis is the subject or lot of debate within the software testing community the general rules of thumb around this topic are given belowhowever it should be borne in mind that these are guidelines rather than hard and fast rules avoid more than or mocks per test you should avoid more than - mocks as the mocks themselves the get harder to manage many also consider that if you need more then - mocks per test then there are probably some underlying design issues that need to be considered for exampleif you are testing python class then that class may have too many dependencies alternatively the class may have too many responsibilities and should be broken down into several independent classeseach with distinct responsibility another cause might be that the class' behaviour may not be encapsulated enough and that you are allowing other elements to interact with the class in more informal ways ( the interface between the class and other elements is not clean/exploit enoughthe result is that it may be necessary to refactor your class before progressing with your development and testing only mock you nearest neighbour you should only ever mock your nearest neighbour whether that is functionmethod or object you should try to avoid mocking dependencies of dependencies if you find yourself doing this then it will become harder to configuremaintainunderstand and develop it is also increasingly likely that you are testing the mocks rather than your own functionmethod or class mocking considerations the following provide some rules of thumb to consider when using mocks with your testsdon' over mock--if you do then you can end up just testing the mocks themselves |
19,227 | mocking considerations decide what to mocktypical examples of what to mock include those elements that are not yet availablethose elements that are not by default repeatable (such as live data feedsor those elements of the system that are time consuming or complex decide where to mock such as the interfaces for the unit under test you want to test the unit so any interface it has with another systemfunctionclass might be candidate for mock decide when to mock so that you can determine the boundaries for the test decide how you will implement your mocks for example you need to consider which mocking framework(syou will use or how to mock larger components such as database online resources there is great deal of information available on how to mockwhen to mock and what mock libraries to usehowever the following provides useful starting points for python mockinglibrary documentation on the unitest mock library source mock object framework for python library for python exercises one of the reasons for mocking is to ensure that tests are repeatable in this exercise we will mock out the use of random number generate to ensure that our tests can be easily repeated the following program generates deck of cards and randomly picks card from the deck |
19,228 | mocking for testing import random def create_suite(suite)return (isuitefor in range( )def pick_a_card(deck)print('you picked'position random randint( print(deck[position][ ]"of"deck[position][ ]return (deck[position]set up the data hearts create_suite('hearts'spades create_suite('spades'diamonds create_suite('diamonds'clubs create_suite('clubs'make the deck of cards deck hearts spades diamonds clubs randomly pick from the deck of cards card pick_a_card(deckeach time the program is run different card is pickedfor example in two consecutive runs the following output is obtainedyou picked of clubs you picked of hearts we now want to write test for the pick_a_card(function you should mock out the random randint(function to do this |
19,229 | file input/output |
19,230 | introduction to filespaths and io introduction the operating system is critical part of any computer systems it is comprised of elements that manage the processes that run on the cpuhow memory is utilised and managedhow peripheral devices are used (such as printers and scanners)it allows the computer system to communicate with other systems and it also provide support for the file system used the file system allows programs to permanently store data this data can then be retrieved by applications at later datepotentially after the whole computer has been shut down and restarted the file management system is responsible for managing the creationaccess and modification of the long term storage of data in files this data may be stored locally or remotely on diskstapesdvd drivesusb drives etc although this was not always the casemost modern operating systems organise files into hierarchical structureusually in the form of an inverted tree for example in the following diagram the root of the directory structure is shown as '/this root directory holds six subdirectories in turn the users subdirectory holds further directories and so on(cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science |
19,231 | introduction to filespaths and io each file is contained within directory (also known as folder on some operating systems such as windowsa directory can hold zero or more files and zero or more directories for any give directory there are relationships with other directories as shown below for the directory jhuntthe root directory is the starting point for the hierarchical directory tree structure child directory of given directory is known as subdirectory the directory that holds the given directory is known as the parent directory at any one timethe directory within which the program or user is currently workingis known as the current working directory user or program can move around this directory structure as required to do this the user can typically either issue series of commands at terminal or command window such as cd to change directory or pwd to print the working directory alternatively graphical user interfaces (guisto operating systems usually include some form of file manager application that allows user to view the file structure in terms of tree the finder program for the mac is shown below with tree structure displayed for pycharmprojects directory similar view is also presented for the windows explorer program |
19,232 | file attributes file attributes file will have set of attributes associated with it such as the date that it was createdthe date it was last updated/modifiedhow large the file is etc it will also typically have an attribute indicating who the owner of the file is this may be the creator of the filehowever the ownership of file can be changed either from the command line or through the gui interface for exampleon linux and mac os the command chown can be used to change the file ownership it can also have other attributes which indicate who can readwrite or execute the file in unix style systems (such as linux and mac os xthese access rights can be specified for the file ownerfor the group that the file is associated with and for all other users the file owner can have rights specified for readingwriting and executing file these are usually represented by the symbols ' ''wand 'xrespectively for example the following uses the symbolic notation associated with unix files and indicates that the file owner is allowed to readwrite and execute filehere the first dash is left blank as it is to do with special files (or directories)then the next set of three characters represent the permissions for the ownerthe following set of three the permissions for all other users as this example has rwx in |
19,233 | introduction to filespaths and io the first group of three characters this indicates that the user can read ' 'write 'wand execute 'xthe file however the next six characters are all dashes indicating that the group and all other users cannot access the file at all the group that file belongs to is group that can have any number of users as members member of the group will have the access rights as indicated by the group settings on the file as for the owner of file these can be to readwrite or execute the file for exampleif group members are allowed to read and execute filethen this would be shown using the symbolic notation asnow this example indicates that only members of the group can read and execute the filenote that group members cannot write the file (they therefore cannot modify the fileif user is not the owner of filenor member of the group that the file is part ofthen their access rights are in the 'everyone elsecategory again this category can have readwrite or execute permissions for exampleusing the symbolic notationif all users can read the file but are not able to do anything elsethen this would be shown asof course file can mix the above permissions togetherso that an owner may be allowed to readwrite and execute filethe group may be able to read and execute the file but all other users can only read the file this would be shown asin addition to the symbolic notation there is also numeric notation that is used with unix style systems the numeric notation uses three digits to represent the permissions each of the three rightmost digits represents different component of the permissionsownergroupand others each of these digits is the sum of its component bits in the binary numeral system as resultspecific bits add to the sum as it is represented by numeralthe read bit adds to its total (in binary )the write bit adds to its total (in binary )and the execute bit adds to its total (in binary this the following symbolic notations can be represented by an equivalent numeric notationsymbolic notation numeric notation meaning rwx---rwxrwx--rwxrwxrwx readwriteand execute only for owner readwriteand execute for owner and group readwriteand execute for ownergroup and others |
19,234 | file attributes directories have similar attributes and access rights to files for examplethe following symbolic notation indicates that directory (indicated by the ' 'has read and execute permissions for the directory owner and for the group other users cannot access this directorythe permissions associated with file or directory can be changed either using command from terminal or command window (such as chmod which is used to modify the permissions associated with file or directoryor interactively using the file explorer style tool paths path is particular combination of directories that can lead to specific sub directory or file this concept is important as unix/linux/max os and windows file systems represent an inverted tree of directories and files it is thus important to be able to uniquely reference locations with the tree for examplein the following diagram the path /users/jhunt/workspaces/pycharmprojects/furtherpythonis highlighteda path may be absolute or relative an absolute path is one which provides complete sequence of directories from the root of the file system to specific sub directory or file relative path provides sequence from the current working directory to particular subdirectory or file the absolute path will work wherever program or user is currently located within the directory tree howevera relative path may only be relevant in specific location |
19,235 | introduction to filespaths and io for examplein the following diagramthe relative path pycharmprojectsfurtherpythonis only meaningful relative to the directory workspacesnote that an absolute path starts from the root directory (represented by '/'where as relative path starts from particular subdirectory (such as pychamprojects file input/output file input/output (often just referred to as file /oinvolves reading and writing data to and from files the data being written can be in different formats for example common format used in unix/linux and windows systems is the ascii text format the ascii format (or american standard code for information interchangeis set of codes that represent various characters that is widely used by operating systems the following table illustrates some of the ascii character codes and what they representdecimal code character meaning asterisk plus zero one two three uppercase uppercase uppercase uppercase (continued |
19,236 | file input/output (continueddecimal code character meaning lowercase lowercase lowercase lowercase ascii is very useful format to use for text files as they can be read by wide range of editors and browsers these editors and browsers make it very easy to create human readable files howeverprogramming languages such as python often use different set of character encodings such as unicode character encoding (such as utf- unicode is another standard for representing characters using various codes unicode encoding systems offer wider range of possible character encodings than asciifor example the latest version of unicode in may unicode contains repertoire of , characters covering modern and historic scriptsas well as multiple symbol sets and emojis howeverthis means that it can be necessary to translate ascii into unicode ( utf- and vice versa when reading and writing ascii files in python another option is to use binary format for data in file the advantage of using binary data is that there is little or no translation required from the internal representation of the data used in the python program into the format stored in the file it is also often more concise than an equivalent ascii format and it is quicker for program to read and write and takes up less disk space etc howeverthe down side of binary format is that it is not in an easily human readable format it may also be difficult for other programsparticularly those written in other programming languages such as java or #to read the data in the files sequential access versus random access data can be read from (or indeed written toa file either sequentially or via random access approach sequential access to data in file means that the program reads (or writesdata to file sequentiallystarting at the beginning of file and processing the data an item at time until the end of the file is reached the read process only ever moves forward and only to the next item of data to read random access to data file means that the program can read (or writedata anywhere into the file at any time that is the program can position itself at particular point in the file (or rather pointer can be positioned within the fileand it can then start to read (or writeat that point if it is reading then it will read the next data item relative to the pointer rather than the start of the file if it is writing data then it will write data from that point rather than at the end of the file if there is already data at that point in the file then it will be over written this type of access is |
19,237 | introduction to filespaths and io also known as direct access as the computer program needs to know where the data is stored within the file and thus goes directly to that location for the data in some cases the location of the data is recorded in an index and thus is also known as indexed access sequential file access has advantages when program needs to access information in the same order each time the data is read it is also is faster to read or write all the data sequentially than via direct access as there is no need to move the file pointer around random access files however are more flexible as data does not need to be written or read in the order in which it is obtained it is also possible to jump to just the location of the data required and read that data (rather than needing to sequentially read through all the data to find the data items of interest files and / in python in the remainder of this section of the book we will explore the basic facilities provided for reading and writing files in python we will also look at the underlying streams model for file / after this we will explore the widely used csv and excel file formats and libraries available to support those this section concludes by exploring the regular expression facilities in python while this last topic is not strictly part of file / it is often used to parse data read from files to screen out unwanted information online resources see the following online resources for information on the topics in this |
19,238 | reading and writing files introduction reading data from and writing data to file is very common within many programs python provides large amount of support for working with files of various types this introduces you to the core file io functionality in python obtaining references to files reading fromand writing totext files in python is relatively straightforward the built in open(function creates file object for you that you can use to read andor write data from andor to file the function requires as minimum the name of the file you want to work with optionally you can specify the access mode ( readwriteappend etc if you do not specify mode then the file is open in read-only mode you can also specify whether you want the interactions with the file to be buffered which can improve performance by grouping data reads together the syntax for the open(function is file_object open(file_nameaccess_modebufferingwhere file_name indicates the file to be accessed access_mode the access_mode determines the mode in which the file is to be openedi readwriteappendetc complete list of possible values is given below in the table this is an optional parameter and the default file access mode is read ( (cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science |
19,239 | reading and writing files buffering if the buffering value is set to no buffering takes place if the buffering value is line buffering is performed while accessing file the access_mode values are given in the following table mode description opens file for reading only the file pointer is placed at the beginning of the file this is the default mode opens file for reading only in binary format the file pointer is placed at the beginning of the file this is the default mode opens file for both reading and writing the file pointer placed at the beginning of the file opens file for both reading and writing in binary format the file pointer placed at the beginning of the file opens file for writing only overwrites the file if the file exists if the file does not existcreates new file for writing opens file for writing only in binary format overwrites the file if the file exists if the file does not existcreates new file for writing opens file for both writing and reading overwrites the existing file if the file exists if the file does not existcreates new file for reading and writing opens file for both writing and reading in binary format overwrites the existing file if the file exists if the file does not existcreates new file for reading and writing opens file for appending the file pointer is at the end of the file if the file exists that isthe file is in the append mode if the file does not existit creates new file for writing opens file for appending in binary format the file pointer is at the end of the file if the file exists that isthe file is in the append mode if the file does not existit creates new file for writing opens file for both appending and reading the file pointer is at the end of the file if the file exists the file opens in the append mode if the file does not existit creates new file for reading and writing opens file for both appending and reading in binary format the file pointer is at the end of the file if the file exists the file opens in the append mode if the file does not existit creates new file for reading and writing rb rrbw wb wwba ab aabthe file object itself has several useful attributes such as file closed returns true if the file has been closed (can no longer be accessed because the close(method has been called on itfile mode returns the access mode with which the file was opened file name the name of the file the file close(method is used to close the file once you have finished with it this will flush any unwritten information to the file (this may occur because of bufferingand will close the reference from the file object to the actual underlying operating system file this is important to do as leaving reference to file open can cause problems in larger applications as typically there are only certain number of file references possible at one time and over long period of time these |
19,240 | obtaining references to files may all be used up resulting in future errors being thrown as files can no longer be opened the following short code snippet illustrates the above ideasfile open('myfile txt'' +'print('file name:'file nameprint('file closed:'file closedprint('file mode:'file modefile close(print('file closed now:'file closedthe output from this isfile namemyfile txt file closedfalse file moderfile closed nowtrue reading files of coursehaving set up file object we want to be able to either access the contents of the file or write data to that file (or do bothreading data from text file is supported by the read()readline(and readlines(methodsthe read(method this method will return the entire contents of the file as single string the readline(method reads the next line of text from file it returns all the text on one line up to and including the newline character it can be used to read file line at time the readlines(method returns list of all the lines in filewhere each item of the list represents single line note that once you have read some text from file using one of the above operations then that line is not read again thus using readlines(would result in further readlines(returning an empty list whatever the contents of the file the following illustrates using the readlines(method to read all the text in text file into program and then print each line out in turnfile open('myfile txt'' 'lines file readlines(for line in linesprint(lineend=''file close( |
19,241 | reading and writing files notice that within the for loop we have indicated to the print function that we want the end character to be rather than newlinethis is because the line string already possesses the newline character read from the file file contents iteration as suggested by the previous exampleit is very common to want to process the contents of file one line at time in fact python makes this extremely easy by making the file object support iteration file iteration accesses each line in the file and makes that line available to the for loop we can therefore writefile open('myfile txt'' 'for line in fileprint(lineend=''file close(it is also possible to use the list comprehension to provide very concise way to load and process lines in file into list it is similar to the effect of readlines(but we are now able to pre-process the data before creating the listfile open('myfile txt'' 'lines [line upper(for line in filefile close(print(lines writing data to files writing string to file is supported by the write(method of coursethe file object we create must have an access mode that allows writing (such as ' 'note that the write method does not add newline character (represented as '\ 'to the end of the string--you must do this manually an example short program to write text file is given belowprint('writing file' open('my-new-file txt'' ' write('hello from python!!\ ' write('working with files is easy \ ' write('it is cool \ ' close( |
19,242 | writing data to files this creates new file called my-new-file txt it then writes three strings to the file each with newline character on the endit then closes the file the effect of this is to create new file called myfile txt with three lines in it using files and with statements like several other types where it is important to shut down resourcesthe file object class implements the context manager protocol and thus can be used with the with statement it is therefore common to write code that will open file using the with as structure thus ensuring that the file will be closed when the block of code is finished withfor examplewith open('my-new-file txt'' 'as flines file readlines(for line in linesprint(lineend='' the fileinput module in some situationsyou may need to read the input from several files in one go you could do this by opening each file independently and then reading the contents and appending that contents to list etc howeverthis is common enough requirement that the fileinput module provides function fileinput input(that can take list of files and treat all the files as single input significantly simplifying this processfor examplewith fileinput input(files=('spam txt''eggs txt')as ffor line in fprocess(line |
19,243 | reading and writing files features provided by the fileinput module include return the name of the file currently being read return the integer "file descriptorfor the current file return the cumulative line number of the line that has just been read return the line number in the current file before the first line has been read this returns boolean function that indicates if the current line just read is the first line of its file some of these are illustrated belowwith fileinput input(files=('textfile txt''textfile txt')as fline readline(print(' filename():' filename()print(' isfirstline():' isfirstline()print(' lineno():' lineno()print(' filelineno():' filelineno()for line in fprint(lineend='' renaming files file can be renamed using the os rename(function this function takes two argumentsthe current filename and the new filename it is part of the python os module which provides methods that can be used to perform range of file-processing operations (such as renaming fileto use the moduleyou will first need to import it an example of using the rename function is given belowimport os os rename('myfileoriginalname txt',myfilenewname txt' deleting files file can be deleted using the os remove(method this method deletes the file specified by the filename passed to it againit is part of the os module and therefore this must be imported firstimport os os remove('somefilename txt' |
19,244 | random access files random access files all the examples presented so far suggest that files are accessed sequentiallywith the first line read before the second and so on although this is (probablythe most common approach it is not the only approach supported by pythonit is also possible to use random-access approach to the contents within file to understand the idea of random file access it is useful to understand that we can maintain pointer into file to indicate where we are in that file in terms of reading or writing data before anything is read from file the pointer is before the beginning of the file and reading the first line of text would for exampleadvance the point to the start of the second line in the file etc this idea is illustrated belowwhen randomly accessing the contents of file the programmer manually moves the pointer to the location required and reads or writes text relative to that pointer this means that they can move around in the file reading and writing data the random-access aspect of file is provided by the seek method of the file objectfile seek (offsetwhencethis method determines where the next read or write operation (depending on the mode used in the open(calltakes place in the above the offset parameter indicates the position of the readwrite pointer within the file the move can also be forwards or backwards (represented by negative offsetthe optional whence parameter indicates where the offset is relative to the values used for whence are |
19,245 | reading and writing files indicates that the offset is relative to start of file (the default means that the offset is relative to the current pointer position indicates the offset is relative to end of file thuswe can move the pointer to position relative to the start of the fileto the end of the fileor to the current position for examplein the following sample code we create new text file and write set of characters into that file at this point the pointer is positioned after the 'zin the file howeverwe then use seek(to move the point to the th character in the file and now write 'hello'next we reposition the pointer to the th character in the file and write out 'boowe then close the file finallywe read all the lines from the file using with as statement and the open(function and from this we will see that the text is the file is now abcdefboojhellopqrstuvwxyzf open('text txt'' ' write('abcdefghijklmnopqrstuvwxyz\ ' seek( , write('hello' seek( write ('boo' close(with open('text txt'' 'as ffor line in fprint(lineend='' directories both unix like systems and windows operating systems are hierarchical structures comprising directories and files the os module has several functions that can help with creatingremoving and altering directories these includemkdir(this function is used to create directoryit takes the name of the directory to create as parameter if the directory already exists fileexistserror is raised chdir(this function can be used to change the current working directory this is the directory that the application will read fromwrite to by default getcwd(this function returns string representing the name of the current working directory rmdir(this function is used to removedelete directory it takes the name of the directory to delete as parameter listdir(this function returns list containing the names of the entries in the directory specified as parameter to the function (if no name is given the current directory is used |
19,246 | directories simple example illustrates the use of some of these functions is given belowimport os print('os getcwd(:'os getcwd()print('list contents of directory'print(os listdir()print('create mydir'os mkdir('mydir'print('list the updated contents of directory'print(os listdir()print('change into mydir directory'os chdir('mydir'print('os getcwd(:'os getcwd()print('change back to parent directory'os chdir('print('os getcwd(:'os getcwd()print('remove mydir directory'os rmdir('mydir'print('list the resulting contents of directory'print(os listdir()note that is short hand for the parent directory of the current directory and is short hand for the current directory an example of the type of output generated by this program for specific set up on mac is given belowos getcwd(/users/shared/workspaces/pycharm/pythonintro/textfiles list contents of directory ['my-new-file txt''myfile txt''textfile txt''textfile txt'create mydir list the updated contents of directory ['my-new-file txt''myfile txt''textfile txt''textfile txt''mydir'change into mydir directory os getcwd(/users/shared/workspaces/pycharm/pythonintro/textfiles/mydir change back to parent directory os getcwd(/users/shared/workspaces/pycharm/pythonintro/textfiles remove mydir directory list the resulting contents of directory ['my-new-file txt''myfile txt''textfile txt''textfile txt' |
19,247 | reading and writing files temporary files during the execution of many applications it may be necessary to create temporary file that will be created at one point and deleted before the application finishes it is of course possible to manage such temporary files yourself howeverthe tempfile module provides range of facilities to simplify the creation and management of these temporary files within the tempfile module temporaryfilenamedtemporaryfiletemporarydirectoryand spooledtemporaryfile are high-level file objects which provide automatic cleanup of temporary files and directories these objects implement the context manager protocol the tempfile module also provides the lower-level function mkstemp(and mkdtemp(that can be used to create temporary files that require the developer to management them and delete them at an appropriate time the high-level feature for the tempfile module aretemporaryfile(mode=' + 'return an anonymous file-like object that can be used as temporary storage area on completion of the managed context (via with statementor destruction of the file objectthe temporary file will be removed from the filesystem note that by default all data is written to the temporary file in binary format which is generally more efficient namedtemporaryfile(mode=' + 'this function operates exactly as temporaryfile(doesexcept that the file has visible name in the file system spooledtemporaryfile(max_size= mode=' + 'this function operates exactly as temporaryfile(doesexcept that data is spooled in memory until the file size exceeds max_sizeor until the file' fileno (method is calledat which point the contents are written to disk and operation proceeds as with temporaryfile(temporarydirectory(suffix=noneprefix=nonedir=nonethis function creates temporary directory on completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem the lower level functions includemkstemp(creates temporary file that is only readable or writable by the user who created it mkdtemp(creates temporary directory the directory is readablewritableand searchable only by the creating user id gettempdir(return the name of the directory used for temporary files this defines the default value for the default temporary directory to be used with the other functions in this module an example of using the temporaryfile function is given below this code imports the tempfile module then prints out the default directory used for |
19,248 | temporary files temporary files it then creates temporaryfile object and prints its name and mode (the default mode is binary but for this example we have overwritten this so that plain text is usedwe have then written line to the file using seek we are repositioning ourselves at the start of the file and then reading the line we have just written import tempfile print('tempfile gettempdir():'tempfile gettempdir()temp tempfile temporaryfile(' +'print('temp name:'temp nameprint('temp mode:'temp modetemp write('hello world!'temp seek( line temp readline(print('line:'linethe output from this when run on an apple mac istempfile gettempdir()/var/folders/ / nrnt pn ypg dq gn/ temp name temp modewlinehello worldnote that the file name is ' and that the temporary directory is not meaningful name working with paths the pathlib module provides set of classes representing filesystem pathsthat is paths through the hierarchy of directories and files within an operating systems file structure it was introduced in python the core class in this module is the path class path object is useful because it provides operations that allow you to manipulate and manage the path to file or directory the path class also replicates some of the operations available from the os module (such as mkdirrename and rmdirwhich means that it is not necessary to work directly with the os module path object is created using the path constructor functionthis function actually returns specific type of path depending on the type of operating system being used such as windowspath or posixpath (for unix style systems |
19,249 | reading and writing files the path(constructor takes the path to create for example ' :/mydir(on windowsor '/users/user /mydiron mac or '/var/tempon linux etc you can then use several different methods on the path object to obtain information about the path such asexists(returns true of false depending on whether the path points to an existing file or directory is_dir(returns true if the path points to directory false if it references file false is also returned if the path does not exist is_file(returns true of the path points to fileit returns false if the path does not exist or the path references directory absolute( path object is considered absolute if it has both root and (if appropriatea drive is_absolute(returns boolean value indicating whether the path is absolute or not an example of using some of these methods is given belowfrom pathlib import path print('create path object for current directory' path('print(' :'pprint(' exists():' exists()print(' is_dir():' is_dir()print(' is_file():' is_file()print(' absolute():' absolute()sample output produced by this code snippet iscreate path object for current directory pp exists()true is_dir()true is_file()false absolute()/users/shared/workspaces/pycharm/pythonintro/textfiles there are also several methods on the path class that can be used to create and remove directories and files such asmkdir(is used to create directory path if it does not exist if the path already existsthen fileexistserror is raised rmdir(remove this directorythe directory must be empty otherwise an error will be raised |
19,250 | working with paths rename(targetrename this file or directory to the given target unlink(removes the file referenced by the path object joinpath(*otherappends elements to the path object path joinpath('temp'with_name(new_namereturn new path object with the name changed the '/operator can also be used to create new path objects from existing paths for example path'test''outputwhich would append the directories test and out to the path object two path class methods can be used to obtain path objects representing key directories such as the current working directory (the directory the program is logically in at that pointand the home directory of the user running the programpath cwd(return new path object representing the current directory path home(return new path object representing the user' home directory an example using several of the above features is given below this example obtains path object representing the current working directory and then appends 'textto this the result path object is then checked to see if the path exists (on the computer running the program)assuming that the path does not exist it is created and the exists(method is rerun path cwd(print('set up new directory'newdir 'testprint('check to see if newdir exists'print('newdir exists():'newdir exists()print('create new dir'newdir mkdir(print('newdir exists():'newdir exists()the effect of creating the directory can be seen in the outputset up new directory check to see if newdir exists newdir exists()false create new dir newdir exists()true very useful method in the path object is the glob(patternmethod this method returns all elements within the path that meet the pattern specified for example path glob('py'will return all the files ending py within the current path |
19,251 | reading and writing files note that '**/pywould indicate the current directory and any sub directory for examplethe following code will return all files where the file name ends with txtfor given pathprint('- for file in path glob('txt')print('file:'fileprint('- an example of the output generated by this code isfilemy-new-file txt filemyfile txt filetextfile txt filetextfile txt paths that reference file can also be used to read and write data to that file for example the open(method can be used to open file that by default allows file to be readopen(mode=' 'this can be used to open the file referenced by the path object this is used below to read the contents of file line at time (note that with as statement is used here to ensure that the file represented by the path is closed) path('mytext txt'with open(as fprint( readline()howeverthere are also some high-level methods available that allow you to easily write data to file or read data from file these include the path methods write_text and read_text methodswrite_text(dataopens the file pointed to in text mode and writes the data to it and then closes the file read_text(opens the file in read modereads the text and closes the fileit then returns the contents of the file as string |
19,252 | working with paths these are used below dir path(/test'print('create new file'newfile dir 'text txtprint('write some text to file'newfile write_text('hello python world!'print('read the text back again'print(newfile read_text()print('remove the file'newfile unlink(which generates the following outputcreate new file write some text to file read the text back again hello python worldremove the file online resources see the following online resources for information on the topics in this tutorial on file input and output objects gnu zip files exercise the aim of this exercise is to explore the creation ofand access tothe contents of file you should write two programsthese programs are outlined below create program that will write todays date into file the name of the file can be hard coded or supplied by the user you can use the datetime today( |
19,253 | reading and writing files function to obtain the current date and time you can use the str(function to convert this date time object into string so that it can be written out to file create second program to reload the date from the file and convert the string into date object you can use the datetime strptime(function to convert string into date time object (see datetime html#datetime datetime strptime for documentation on this functionthis functions takes string containing date and time in it and second string which defines the format expected if you use the approach outlined in step above to write the string out to file then you should find that the following defines an appropriate format to parse the date_str so that date time object can be createddatetime_object datetime strptime(date_str'% -% -% % :% :% % ' |
19,254 | stream io introduction in this we will explore the stream / model that under pins the way in which data is read from and written to data sources and sinks one example of data source or sink is file but another might be byte array this model is actually what sits underneath the file access mechanisms discussed in the previous it is not actually necessary to understand this model to be able to read and write data to and from filehowever in some situations it is useful to have an understanding of this model so that you can modify the default behaviour when necessary the remainder of this first introduces the stream modeldiscusses python streams in general and then presents the classes provided by python it then considers what is the actual effect of using the open(function presented in the last what is streamstreams are objects which serve as sources or sinks of data at first this concept can seem bit strange the easiest way to think of stream is as conduit of data flowing from or into pool some streams read data straight from the "source of the dataand some streams read data from other streams these latter streams then do some "usefulprocessing of the data such as converting the raw data into specific format the following figure illustrates this idea (cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science |
19,255 | stream io in the above figure the initial fileio stream reads raw data from the actual data source (in this case filethe bufferedreader then buffers the data reading process for efficiency finally the textiowrapper handles string encodingthat is it converts strings from the typical ascii representation used in file into the internal representation used by python (which uses unicodeyou might ask at this point why have streams model at allafter all we read and wrote data to files without needing to know about streams in the last the answer is that stream can read or write data to or from source of data rather than just from file of course file can be source of data but so can socketa pipea stringa web service etc it is therefore more flexible data / model python streams the python io module provides python' main facilities for dealing with data input and output there are three main types of input/output these are text /obinary / and raw io these categories can be used with various types of data source/sinks whatever the categoryeach concrete stream can have number of properties such as being read-onlywrite-only or read-write it can also support sequential access or random access depending on the nature of the underlying data sink for examplereading data from socket or pipe is inherently sequential where as reading data from file can be performed sequentially or via random access approach whichever stream is used howeverthey are aware of the type of data they can process for exampleattempting to supply string to binary write-only stream will raise typeerror as indeed will presenting binary data to text stream etc as suggested by this there are number of different types of stream provided by the python io module and some of these are presented below |
19,256 | python streams the abstract iobase class is at the root of the stream io class hierarchy below this class are stream classes for unbuffered and buffered io and for text oriented io iobase this is the abstract base class for all / stream classes the class provides many abstract methods that subclasses will need to implement the iobase class (and its subclassesall support the iterator protocol this means that an iobase object (or an object of subclasscan iterate over the input data from the underling stream iobase also implements the context manager protocol and therefore it can be used with the with and with-as statements the iobase class defines core set of methods and attributes includingclose(flush and close the stream closed an attribute indicating whether the stream is closed flush(flush the write buffer of the stream if applicable readable(returns true if the stream can be read from readline(size=- return line from the stream if size is specified at most size bytes will be read readline(hint=- read list of lines if hint is specified then it is used to control the number of lines read seek(offset[whence]this method moves the current the stream position/pointer to the given offset the meaning of the offset depends on the whence parameter the default value for whence is seek_set seek_set or seek from the start of the stream (the default)offset must either be number returned by textiobase tell()or zero any other offset value produces undefined behaviour seek_cur or "seekto the current positionoffset must be zerowhich is no-operation (all other values are unsupportedseek_end or seek to the end of the streamoffset must be zero (all other values are unsupported |
19,257 | stream io seekable(does the stream support seek(tell(return the current stream position/pointer writeable(returns true if data can be written to the stream writelines(lineswrite list of lines to the stream raw io/unbuffered io classes raw io or unbuffered io is provided by the rawiobase and fileio classes rawiobase this class is subclass of iobase and is the base class for raw binary (aka unbufferedi/ raw binary / typically provides low-level access to an underlying os device or apiand does not try to encapsulate it in high-level primitives (this is the responsibility of the buffered / and text / classes that can wrap raw / streamthe class adds methods such asread(size=- this method reads up to size bytes from the stream and returns them if size is unspecified or - then all available bytes are read readall(this method reads and returns all available bytes within the stream readint(bthis method reads the bytes in the stream into pre-allocatedwritable bytes-like object ( into byte arrayit returns the number of bytes read write(bthis method writes the data provided by ( bytes -like object such as byte arrayinto the underlying raw stream fileio the fileio class represents raw unbuffered binary io stream linked to an operating system level file when the fileio class is instantiated it can be given file name and the mode (such as 'ror 'wetc it can also be given flag to indicate whether the file descriptor associated with the underlying os level file should be closed or not this class is used for the low-level reading of binary data and is at the heart of all file oriented data access (although it is often wrapped by another stream such as buffered reader or writer binary io/buffered io classes binary io aka buffered io is filter stream that wraps lower level rawiobase stream (such as fileio streamthe classes implementing buffered io all extend the bufferediobase class and arebufferedreader when reading data from this objecta larger amount of data may be requested from the underlying raw streamand kept in an internal buffer the buffered data can then be returned directly on subsequent reads |
19,258 | binary io/buffered io classes bufferedwriter when writing to this objectdata is normally placed into an internal buffer the buffer will be written out to the underlying rawiobase object under various conditionsincludingwhen the buffer gets too small for all pending datawhen flush(is calledwhen the bufferedwriter object is closed or destroyed bufferedrandom buffered interface to random access streams it supports seek(and tell(functionality bufferedrwpair buffered / object combining two unidirectional rawiobase objects one readablethe other writeable--into single bidirectional endpoint each of the above classes wrap lower level byte oriented stream class such as the io fileio classfor examplef io fileio('data dat'br io bufferedreader(fprint(br read()this allows data in the form of bytes to be read from the file 'data datyou can of course also read data from different sourcesuch as an in memory bytesio objectbinary_stream_from_file io bufferedreader(io bytesio( 'starship png')bytes binary_stream_from_file read( print(bytesin this example the data is read from the bytesio object by the bufferedreader the read(method is then used to read the first bytesthe output isnote the 'bin front of both the string 'starship pngand the result 'starthis indicates that the string literal should become bytes literal in python bytes literals are always prefixed with 'bor ' 'they produce an instance of the bytes type instead of the str type they may only contain ascii characters the operations supported by buffered streams includefor readingpeek(nreturn up to bytes of data without advancing the stream pointer the number of bytes returned may be less or more than requested depending on the amount of data available read(nreturn bytes of data as bytesif is not supplied (or is negativethe read all available data readl(nread up to bytes of data using single call on the raw data stream |
19,259 | stream io the operations supported by buffered writers includewrite(byteswrites the bytes-like data and returns the number of bytes written flush(this method forces the bytes held in the buffer into the raw stream text stream classes the text stream classes are the textiobase class and its two subclasses textiowrapper and stringio textiobase this is the root class for all text stream classes it provides character and line based interface to stream / this class provides several additional methods to that defined in its parent classread(size=- this method will return at most size characters from the stream as single string if size is negative or noneit will read all remaining data readline(size=- this method will return string representing the current line (up to newline or the end of the data whichever comes firstif the stream is already at eofan empty string is returned if size is specifiedat most size characters will be read seek(offset[whence]change the stream position/pointer by the specified offset the optional whence parameter indicates where the seek should start fromseek_set or (the defaultseek from the start of the stream seek_cur or seek to the current positionoffset must be zerowhich is no-operation seek_end or seek to the end of the streamoffset must be zero tell(returns the current stream position/pointer as an opaque number the number does not usually represent number of bytes in the underlying binary storage write(sthis method will write the string to the stream and return the number of characters written textiowrapper this is buffered text stream that wraps buffered binary stream and is direct subclass of textiobase when textiowrapper is created there are range of options available to control its behaviourio textiowrapper(bufferencoding=noneerrors=nonenewline=no neline_buffering=falsewrite_through=false |
19,260 | text stream classes where buffer is the buffered binary stream encoding represents the text encoding used such as utf- errors defines the error handling policy such as strict or ignore newline controls how line endings are handled for example should they be ignored (noneor represented as linefeedcarriage return or newline/carriage return etc line_buffering if true then flush(is implied when call to write contains newline character or carriage return write_through if true then call to write is guaranteed not to be buffered the textiowrapper is wrapped around lower level binary buffered / streamfor examplef io fileio('data txt'br io bufferedreader(ftext_stream io textiowrapper(br'utf- 'stringio this is an in memory stream for text / the initial value of the buffer held by the stringio object can be provided when the instance is createdfor examplein_memory_text_stream io stringio('to be or not to be that is the question'print('in_memory_text_stream'in_memory_text_streamprint(in_memory_text_stream getvalue()in_memory_text_stream close(this generatesin_memory_text_stream to be or not to be that is the question note that the underlying buffer (represented by the string passed into the stringio instanceis discarded when the close(method is called the getvalue(method returns string containing the entire contents of the buffer if it is called after the stream was closed then an error is generated stream properties it is possible to query stream to determine what types of operations it supports this can be done using the readable()seekable(and writeable(methods for example |
19,261 | stream io io fileio('myfile txt'br io bufferedreader(ftext_stream io textiowrapper(brencoding='utf- 'print('text_stream'text_streamprint('text_stream readable():'text_stream readable()print('text_stream seekable()'text_stream seekable()print('text_stream writeable()'text_stream writable()text_stream close(the output from this code snippet istext_stream text_stream readable()true text_stream seekable(true text_stream writeable(false closing streams all opened streams must be closed howeveryou can close the top level stream and this will automatically close lower level streamsfor examplef io fileio('data txt'br io bufferedreader(ftext_stream io textiowrapper(br'utf- 'print(text_stream read()text_stream close( returning to the open(function if streams are so good then why don' you use them all the timewell actually in python you dothe core open function (and indeed the io open(functionboth return stream object the actual type of object returned depends on the file mode specifiedwhether buffering is being used etc for example |
19,262 | returning to the open(function import io text stream open('myfile txt'mode=' 'encoding='utf- 'print( binary io aka buffered io open('myfile dat'mode='rb'print( open('myfile dat'mode='wb'print( raw io aka unbufferedf io open('starship png'mode='rb'buffering= print( when this short example is run the output isas you can see from the outputfour different types of object have been returned from the open(function the first is textiowrapperthe second bufferedreaderthe third bufferedwriter and the final one is fileio object this reflects the differences in the parameters passed into the open ( function for examplef references io textiowrapper because it must encode (convertthe input text into unicode using the utf- encoding scheme while holds io bufferedreader because the mode indicates that we want to read binary data while holds io bufferedwriter because the mode used indicates we want to write binary data the final call to open returns fileio because we have indicated that we do not want to buffer the data and thus we can use the lowest level of stream object in general the following rules are applied to determine the type of object returned based on the modes and encoding specifiedclass mode buffering fileio bufferedreader bufferedwriter bufferedrandom textiowrapper binary 'rb'wb'rb+'wb+'ab+any text no yes yes yes yes |
19,263 | stream io note that not all mode combinations make sense and thus some combinations will generate an error in general you don' therefore need to worry about which stream you are using or what that stream doesnot least because all the streams extend the iobase class and thus have common set of methods and attributes howeverit is useful to understand the implications of what you are doing so that you can make better informed choices for examplebinary streams (that do less processingare faster than unicode oriented streams that must convert from ascii into unicode also understanding the role of streams in input and output can also allow you to change the source and destination of data without needing to re-write the whole of your application you can thus use file or stdin for testing and socket for reading data in production online resources see the following online resources for information on the topics in this library guide to the core tools available for working with streams exercise use the underlying streams model to create an application that will write binary data to file you can use the 'bprefix to create binary literal to be writtenfor example 'hello worldnext create another application to reload the binary data from the file and print it out |
19,264 | working with csv files introduction this introduces module that supports the generation of csv (or comma separated valuesfiles csv files the csv (comma separated valuesformat is the most common import and export format for spreadsheets and databases howevercsv is not precise standard with multiple different applications having different conventions and specific standards the python csv module implements classes to read and write tabular data in csv format as part of this it supports the concept of dialect which is csv format used by specific application or suite of programsfor exampleit supports an excel dialect this allows programmers to say"write this data in the format preferred by excel,or "read data from this file which was generated by excel,without knowing the precise details of the csv format used by excel programmers can also describe the csv dialects understood by other applications or define their own special-purpose csv dialects the csv module provides range of functions includingcsv reader (csvfiledialect='excel'**fmtparamsreturns reader object which will iterate over lines in the given csvfile an optional dialect parameter can be given this may be an instance of subclass of the dialect class or one of the strings returned by the list_dialects(function the other optional fmtparams keyword arguments can be given to override individual formatting parameters in the current dialect (cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science |
19,265 | working with csv files csv writer (csvfiledialect='excel'**fmtparamsreturns writer object responsible for converting the user' data into delimited strings on the given csvfile an optional dialect parameter provided the fmtparams keyword arguments can be given to override individual formatting parameters in the current dialect csv list_dialects(return the names of all registered dialects for example on mac os the default list of dialects is ['excel''excel-tab''unix'the csv writer class csv writer is obtained from the csv writer(function the csvwriter supports two methods used to write data to the csv filecsvwriter writerow(rowwrite the row parameter to the writer' file objectformatted according to the current dialect csvwriter writerows(rowswrite all elements in rows (an iterable of row objects as described aboveto the writer' file objectformatted according to the current dialect writer objects also have the following public attributecsvwriter dialect read-only description of the dialect in use by the writer the following program illustrates simple use of the csv module which creates file called sample csv as we have not specified dialectthe default 'exceldialect will be used the writerow(method is used to write each comma separate list of strings to the csv file print('crearting csv file'with open('sample csv'' 'newline=''as csvfilewriter csv writer(csvfilewriter writerow(['she loves you''sept ']writer writerow([' want to hold your hand''dec ']writer writerow(['cant buy me love''apr ']writer writerow([' hard days night''july ']the resulting file can be viewed as shown below |
19,266 | csv files howeveras it is csv filewe can also open it in excelthe csv reader class csv reader object is obtained from the csv reader(function it implements the iteration protocol if csv reader object is used with for loop then each time round the loop it supplies the next row from the csv file as listparsed according to the current csv dialect reader objects also have the following public attributescsvreader dialect read-only description of the dialect in use by the parser csvreader line_num the number of lines read from the source iterator this is not the same as the number of records returnedas records can span multiple lines the following provides very simple example of reading csv file using csv reader objectprint('starting to read csv file'with open('sample csv'newline=''as csvfilereader csv reader(csvfilefor row in readerprint(*rowsep=''print('done reading' |
19,267 | working with csv files the output from this programbased on the sample csv file created earlier isstarting to read csv file she loves yousept want to hold your handdec cant buy me loveapr hard days nightjuly done reading the csv dictwriter class in many cases the first row of csv file contains set of names (or keysthat define the fields within the rest of the csv that is the first row gives meaning to the columns and the data held in the rest of the csv file it is therefore very useful to capture this information and to structure the data written to csv file or loaded from csv file based on the keys in the first row the csv dictwriter returns an object that can be used to write values into the csv file based on the use of such named columns the file to be used with the dictwriter is provided when the class is instantiated import csv with open('names csv'' 'newline=''as csvfilefieldnames ['first_name''last_name''result'writer csv dictwriter(csvfilefieldnames=fieldnameswriter writeheader(writer writerow({'first_name''john''last_name''smith''result }writer writerow({'first_name''jane''last_name''lewis''result' }writer writerow({'first_name''chris''last_name''davies''result }note that when the dictwriter is created list of the keys must be provided that are used for the columns in the csv file the method writeheader(is then used to write the header row out to the csv file the method writerow(takes dictionary object that has keys based on the keys defined for the dictwriter these are then used to write data out to the csv (note the order of the keys in the dictionary is not importantin the above example code the result of this is that new file called names csv is created which can be opened in excelof courseas this is csv file it can also be opened in plain text editor as well |
19,268 | csv files the csv dictreader class as well as the csv dictwriter there is csv dictreader the file to be used with the dictreader is provided when the class is instantiated as with the dictreader the dictwriter class takes list of keys used to define the columns in the csv file if the headings to be used for the first row can be provided although this is optional (if set of keys are not providedthen the values in the first row of the csv file will be used as the fieldnamesthe dictreader class provides several useful features including the fieldnames property that contains list of the keys/headings for the csv file as defined by the first row of the file the dictreader class also implements the iteration protocol and thus it can be used in for loop in which each row (after the first rowis returned in turn as dictionary the dictionary object representing each row can then be used to access each column value based on the keys defined in the first row an example is shown below for the csv file created earlierimport csv print('starting to read dict csv example'with open('names csv'newline=''as csvfilereader csv dictreader(csvfilefor heading in reader fieldnamesprint(headingend='print('\ 'for row in readerprint(row['first_name']row['last_name']row['result']print('done' |
19,269 | working with csv files this generates the following outputstarting to read dict csv example first_name last_name result john smith jane lewis chris davies done online resources see the following online resources for information on the topics in this on csv files reading csv files exercises in this exercise you will create csv file based on set of transactions stored in current account to do this first define new account class to represent type of bank account when the class is instantiated you should provide the account numberthe name of the account holderan opening balance and the type of account (which can be string representing 'current''depositor 'investmentetc this means that there must be an __init__ method and you will need to store the data within the object provide three instance methods for the accountdeposit(amount)withdraw(amountand get_balance(the behaviour of these methods should be as expecteddeposit will increase the balancewithdraw will decrease the balance and get_balance(returns the current balance your account class should also keep history of the transactions it is involved in transaction is record of deposit or withdrawal along with an amount note that the initial amount in an account can be treated as an initial deposit |
19,270 | exercises the history could be implemented as list containing an ordered sequence to transactions transaction itself could be defined by class with an action (deposit or withdrawaland an amount each time withdrawal or deposit is made new transaction record should be added to transaction history list next provide function (which could be called something like write_account_transactions_to_csv()that can take an account and then write each of the transactions it holds out to csv filewith each transaction type and the transaction amount separated by comma the following sample application illustrates how this function might be usedprint('starting'acc accounts currentaccount(' ''john' acc deposit( acc withdraw( print('writing account transactions'write_account_transaction_to_csv('accounts csv'accprint('done'the contents of the csv file would then be |
19,271 | working with excel files introduction this introduces the openpyxl module that can be used when working with excel files excel is software application developed by microsoft that allows users to work with spreadsheets it is very widely used tool and files using the excel file format are commonly encountered within many organisations it is in effect the industry standard for spreadsheets and as such is very useful tool to have in the developers toolbox excel files although csv files are convenient and simple way to handle datait is very common to need to be able to read or write excel files directly to this end there are several libraries available in python for this purpose one widely used library is the openpyxl library this library was originally written to support access to excel files it is an open source project and is well documented the openpyxl library provides facilities for reading and writing excel workbookscreating/accessing excel worksheetscreating excel formulascreating graphs (with support from additional modulesas openpyxl is not part of the standard python distribution you will need to install the library yourself using tool such as anaconda or pip ( pip install openpyxlalternativelyif you are using pycharm you will be able to add the openpyxl library to your project (cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science |
19,272 | working with excel files the openpyxl workbook class the key element in the openpyxl library is the workbook class this can be imported from the modulefrom openpyxl import workbook new instance of the (in memoryworkbook can be created using the workbook class (note at this point it is purely structure within the python program and must be saved before an actual excel file is createdwb workbook( the openpyxl worksheet objects workbook is always created with at least one worksheet you can get hold of the currently active worksheet using the workbook active propertyws wb active you can create additional worksheets using the workbookscreate_sheet (methodws wb create_sheet('mysheet'you can access or update the title of the worksheet using the title propertyws title 'new titlethe background colour of the tab holding this title is white by default you can change this providing an rrggbb colour code to the worksheet sheet_properties tabcolor attributefor examplews sheet_properties tabcolor " ba working with cells it is possible to access the cells within worksheet cell can be accessed directly as keys on the worksheetfor examplews[' ' |
19,273 | working with cells or cell ws[' 'this returns cell objectyou can obtain the value of the cell using the value propertyfor example print(cell valuethere is also the worksheet cell(method this provides access to cells using row and column notationd ws cell(row= column= value= row of values can also be added at the current position within the excel file using appendws append([ ]this will add row to the excel file containing and ranges of cells can be accessed using slicingcell_range ws[' ':' 'ranges of rows or columns can also be obtainedcol ws[' 'col_range ws[' : 'row ws[ row_range ws[ : the value of cell can also be an excel formula such as ws[' ''=sum( ) workbook is actually only structure in memoryit must be saved to file for permanent storage these workbooks can be saved using the save(method this method takes filename and writes the workbook out in excel format workbook workbook(workbook save('balances xlsx' sample excel file creation application the following simple application creates workbook with two worksheets it also contains simple excel formula that sums the values held in to other cells |
19,274 | working with excel files from openpyxl import workbook def main()print('starting write excel example with openpyxl'workbook workbook(get the current active worksheet ws workbook active ws title 'my worksheetws sheet_properties tabcolor ' baws[' ' ws[' ' ws[' ''=sum( )ws workbook create_sheet(title='my other sheet'ws [' ' ws append([ ]ws cell(column= row= value= workbook save('sample xlsx'print('done write excel example'if __name__ ='__main__'main(the excel file generated from this can be viewed in excel as shown below |
19,275 | loading workbook from an excel file loading workbook from an excel file of coursein many cases it is necessary not just to create excel files for data export but also to import data from an existing excel file this can be done using the openpyxl load_workbook(function this function opens the specified excel file (in read only mode by defaultand returns workbook object from openpyxl import load_workbook workbook load_workbook(filename='sample xlsx'you can now access list of sheetstheir namesobtain the currently active sheet etc using properties provided by the workbook objectworkbook active returns the active worksheet object workbook sheetnames returns the names (stringsof the worksheets in this workbook workbook worksheets returns list of worksheet objects the following sample application reads the excel file created earlier in this from openpyxl import load_workbook def main()print('starting reading excel file using openpyxl'workbook load_workbook(filename='sample xlsx'print(workbook activeprint(workbook sheetnamesprint(workbook worksheetsprint('- ws workbook['my worksheet'print(ws[' ']print(ws[' 'valueprint(ws[' 'valueprint(ws[' 'valueprint('- for sheet in workbookprint(sheet titleprint('- cell_range ws[' ':' 'for cell in cell_rangeprint(cell[ valueprint('- |
19,276 | working with excel files print('finished reading excel file using openpyxl'if __name__ ='__main__'main(the output from this application is illustrated belowstarting reading excel file using openpyxl ['my worksheet''my other sheet'[ =sum( my worksheet my other sheet =sum( finished reading excel file using openpyxl online resources see the following online resources for information on the topics in this python to excel library exercises using the account class that you created in the last write the account transaction information to an excel file instead of csv file to do this create function called write_account_transaction_to_excel (that takes the name of the excel file and the account to store the function should then write the data to the file using the excel format |
19,277 | exercises the following sample application illustrates how this function might be usedprint('starting'acc accounts currentaccount(' ''john' acc deposit( acc withdraw( print('writing account transactions'write_account_transaction_to_excel('accounts xlsx'accprint('done'the contents of the excel file would then be |
19,278 | regular expressions in python introduction regular expression are very powerful way of processing text while looking for recurring patternsthey are often used with data held in plain text files (such as log files)csv files as well as excel files this introduces regular expressionsdiscusses the syntax used to define regular expression pattern and presents the python re module and its use what are regular expressionsa regular expression (also known as regex or even just reis sequence of characters (lettersnumbers and special charactersthat form pattern that can be used to search text to see if that text contains sequences of characters that match the pattern for exampleyou might have pattern defined as three characters followed by three numbers this pattern could be used to look for such pattern in other strings thusthe following strings either match (or containthis pattern or they do notabc aaa matches the pattern does not match the pattern does not match the pattern (cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science |
19,279 | regular expressions in python regular expression are very widely used for finding information in filesfor example finding all lines in log file associated with specific user or specific operationfor validating input such as checking that string is valid email address or postcode/zip code etc support for regular expressions is wide spread within programming languages such as javac#php and particularly perl python is no exception and has the built-in module re (as well as additional third-party modulesthat support regular expressions regular expression patterns you can define regular expression pattern using any ascii character or number thusthe string 'johncan be used to define regex pattern that can be used to match any other string that contains the characters ' '' '' ''nthus each of the following strings will match this pattern'john hunt'john jones'andrew john smith'mary helen john'john john john' am going to visit the john' once saw film by john waynebut the following strings would not match the pattern'jon daviesin this case because the spelling of john is different 'john williamsin this case because the capital does not match the lowercase 'david jamesin this case because the string does not contain the string johnregular expressions (regexsuse special characters to allow more complex patterns to be described for examplewe can use the special characters '[]to define set of characters that can match for exampleif we want to indicate that the may be capital or lower-case letter then we can write '[jj]'--this indicates that either 'jor 'jcan match the first [jj]ohn--this states that the pattern starts with either capital or lowercase followed by 'ohnnow both 'john williamsand 'john williamswill match this regex pattern |
19,280 | regular expression patterns pattern metacharacters there are several special characters (often referred to as metacharactersthat have specific meaning within regex patternthese are listed in the following tablecharacter description example [ set of characters indicates special sequence (can also be used to escape special charactersany character with the exception of the newline character [ -dcharacters in the sequence 'ato ' '\dindicates the character should be an integer ' hnindicates that there can be any character after the 'jand before the ' "^helloindicates the string must start with 'hello"world$indicates the string must end with 'world"python*indicates we are looking for zero or more times python is in string "info+indicates that we must find info in the string at least once "john?indicates zero or one instances of the 'john"john{ }this indicates we expect to see the 'johnin the string three times " { , }indicates that there can be one or two xs next to each other in the string "true|okindicates we are looking for either true or ok "(abc|xyz){ }indicates that we are looking for the string abc or xyz repeated twice {indicates string must start with the following pattern indicates string must end with the preceding pattern zero or more occurrences of the preceding pattern one or more occurrences of preceding pattern indicates zero or occurrences of the preceding pattern exactly the specified number of occurrences either or (groups together regular expressionyou can then apply another operator to the whole group special sequences special sequence is combination of '\(backslashfollowed by character combination which then has special meaning the following table lists the common special sequences used in regular expressions |
19,281 | regular expressions in python sequence description example \ returns match if the following characters are at the beginning of the string returns match where the specified characters are at the beginning or at the end of word "\athemust start with 'the\ \ \ \ \ \ \ \ \ indicates that the following characters must be present in string but not at the start (or at the endof word returns match where the string contains digits (numbers from - returns match where the string does not contain digits returns match where the string contains white space character returns match where the string does not contain white space character returns match where the string contains any word characters (characters from to zdigits from - and the underscore characterreturns match where the string does not contain any word characters returns match if the following characters are present at the end of the string "\bonor "on\bindicates string must start or end with 'onr"\bonor "on\bmust not start or end with 'on"\ "\ "\ *"\ "\ "\ "hunt\zsets set is sequence of characters inside pair of square brackets which have specific meanings the following table provides some examples set description [jeh[ - [^zxc[ [ - [ - ][ - [ -za-zreturns match where one of the specified characters (je or hare present returns match for any lower-case characteralphabetically between and returns match for any character except zx and returns match where any of the specified digits ( or are present returns match for any digit between and returns match for any two-digit numbers from and returns match for any character alphabetically between and or and |
19,282 | the python re module the python re module the python re module is the built-in module provided by python for working with regular expressions you might also like to examine the third party regex module (see org/project/regexwhich is backwards compatible with the default re module but provides additional functionality working with python regular expressions using raw strings an important point to note about many of the strings used to define the regular expression patterns is that they are preceded by an 'rfor example '/bin/sh$the 'rbefore the string indicates that the string should be treated as raw string raw string is python string in which all characters are treated as exactly thatindividual characters it means that backslash ('\'is treated as literal character rather than as special character that is used to escape the next character for examplein standard string '\nis treated as special character representing newlinethus if we wrote the followings 'hello \ worldprint(swe will get as outputhello world howeverif we prefix the string with an 'rthen we are telling python to treat it as raw string for examples 'hello \ worldprint(sthe output is now hello \ world this is important for regular expression as characters such as backslash ('\'are used within patterns to have special regular expression meaning and thus we do not want python to process them in the normal way |
19,283 | regular expressions in python simple example the following simple python program illustrates the basic use of the re module it is necessary to import the re module before you can use it import re text 'john williamspattern '[jj]ohnprint('looking in'text 'for the pattern'patternif re search(patterntext )print('match has been found'when this program is runwe get the following outputlooking in john williams for the pattern [jj]ohn match has been found if we look at the codewe can see that the string that we are examining contains 'john williamsand that the pattern used with this string indicates that we are looking for sequence of 'jor 'jfollowed by 'ohnto perform this test we use the re search(function passing the regex patternand the text to testas parameters this function returns either none (which is taken as meaning false by the if statementor match object (which always has boolean value of trueas of course 'johnat the start of text does match the patternthe re search(function returns match object and we see the 'match has been foundmessage is printed out both the match object and search(method will be described in more detail belowhoweverthis short program illustrates the basic operation of regular expression the match object match objects are returned by the search(and match(functions they always have boolean value of true the functions match(and search(return none when there is no match and match object when match is found it is therefore possible to use match object with an if statement |
19,284 | working with python regular expressions import re match re search(patternstringif matchprocess(matchmatch objects support range of methods and attributes includingmatch re the regular expression object whose match(or search(method produced this match instance match string the string passed to match(or search(match start([group]match end([group]return the indices of the start and end of the substring matched by group match group(returns the part of the string where there was match the search(function the search(function searches the string for matchand returns match object if there is match the signature of the function isre search(patternstringflags= the meaning of the parameters arepattern this is the regular expression pattern to be used in the matching process string this is the string to be searched flags these (optionalflags can be used to modify the operation of the search the re module defines set of flags (or indicatorsthat can be used to indicate any optional behaviours associated with the pattern these flags includeflag description re ignorecase re locale performs case-insensitive matching interprets words according to the current locale this interpretation affects the alphabetic group (\ and \ )as well as word boundary behavior(\ and \bmakes match the end of line (not just the end of the stringand makes match the start of any line (not just the start of the stringmakes period (dotmatch any characterincluding newline interprets letters according to the unicode character set this flag affects the behavior of \ \ \ \ ignores whitespace within the pattern (except inside set [or when escaped by backslashand treats unescaped as comment marker re multiline re dotall re unicode re verbose |
19,285 | regular expressions in python if there is more than one matchonly the first occurrence of the match will be returnedimport re line 'the price is containsintegers '\ +if re search(containsintegersline )print('line contains an integer'elseprint('line does not contain an integer'in this case the output is line contains an integer another example of using the search(function is given below in this case the pattern to look for defines three alternative strings (that is the string must contain either beatlesadele or gorillaz)import re alternative words music 'beatles|adele|gorillazrequest 'play some adeleif re search(musicrequest)print('set fire to the rain'elseprint('no adele available'in this case we generate the outputset fire to the rain the match(function this function attempts to match regular expression pattern at the beginning of string the signature of this function is given belowre match(patternstringflags= |
19,286 | working with python regular expressions the parameters arepattern this is the regular expression to be matched string this is the string to be searched flags modifier flags that can be used the re match(function returns match object on successnone on failure the difference between matching and searching python offers two different primitive operations based on regular expressionsmatch(checks for match only at the beginning of the stringsearch(checks for match anywhere in the string the findall(function the findall(function returns list containing all matches the signature of this function isre findall(patternstringflags= this function returns all non-overlapping matches of pattern in stringas list of strings the string is scanned left-to-rightand matches are returned in the order found if one or more groups are present in the patternthen list of groups is returnedthis will be list of tuples if the pattern has more than one group if no matches are foundan empty list is returned an example of using the findall(function is given below this example looks for substring starting with two letters and followed by 'aiand single character it is applied to sentence and returns only the sub string 'spainand 'plainimport re str 'the rain in spain stays mainly on the plainresults re findall('[ -za- ]{ }ai 'strprint(resultsfor in resultsprint( |
19,287 | regular expressions in python the output from this program is ['spain''plain'spain plain the finditer(function this function returns an iterator yielding matched objects for the regular expression pattern in the string supplied the signature for this function isre finditer(patternstringflags= the string is scanned left-to-rightand matches are returned in the order found empty matches are included in the result flags can be used to modify the matches the split(function the split(function returns list where the string has been split at each match the syntax of the split(function is re split(patternstringmaxsplit= flags= the result is to split string by the occurrences of pattern if capturing parentheses are used in the regular expression patternthen the text of all groups in the pattern are also returned as part of the resulting list if maxsplit is nonzeroat most maxsplit splits occurand the remainder of the string is returned as the final element of the list flags can again be used to modify the matches import re str 'it was hot summer nightx re split('\ 'strprint(xthe output is ['it''was'' ''hot''summer''night' |
19,288 | working with python regular expressions the sub(function the sub(function replaces occurrences of the regular expression pattern in the string with the repl string re sub(patternreplstringmax= this method replaces all occurrences of the regular expression pattern in string with replsubstituting all occurrences unless max is provided this method returns the modified string import re pattern '(england|wales|scotland)input 'england for footballwales for rugby and scotland for the highland gamesprint(re sub(pattern'england'input )which generatesengland for footballengland for rugby and england for the highland games you can control the number of replacements by specifying the count parameterthe following code replaces the first occurrencesimport re pattern '(england|wales|scotland)input 'england for footballwales for rugby and scotland for the highland gamesx re sub(pattern'wales'input print(xwhich produces wales for footballwales for rugby and scotland for the highland games you can also find out how many substitutions were made using the subn(function this function returns the new string and the number of substitutions in tuple |
19,289 | regular expressions in python import re pattern '(england|wales|scotland)input 'england for footballwales for rugby and scotland for the highland gamesprint(re subn(pattern,'scotland'input )the output from this is('scotland for footballscotland for rugby and scotland for the highland games' the compile(function most regular expression operations are available as both module-level functions (as described aboveand as methods on compiled regular expression object the module-level functions are typically simplified or standardised ways to use the compiled regular expression in many cases these functions are sufficient but if finer grained control is required then compiled regular expression may be used re compile(patternflags= the compile(function compiles regular expression pattern into regular expression objectwhich can be used for matching using its match()search(and other methods as described below the expression' behaviour can be modified by specifying flags value the statementsprog re compile(patternresult prog match(stringare equivalent to result re match(patternstringbut using re compile(and saving the resulting regular expression object for reuse is more efficient when the expression will be used several times in single program compiled regular expression objects support the following methods and attributespattern search(stringposendposscan through string looking for the first location where this regular expression produces match and return corresponding match object return none if no position in the string |
19,290 | working with python regular expressions matches the pattern starting at pos if provided and ending at endpos if this is provided (otherwise process the whole stringpattern match(stringposendpos)if zero or more characters at the beginning of string match this regular expressionreturn corresponding match object return none if the string does not match the pattern the pos and endpos are optional and specify the start and end positions within which to search pattern split(stringmaxsplit )identical to the split(functionusing the compiled pattern pattern findall(string[pos[endpos]])similar to the findall (functionbut also accepts optional pos and endpos parameters that limit the search region like for search(pattern finditer(string[pos[endpos]])similar to the finditer(functionbut also accepts optional pos and endpos parameters that limit the search region like for search(pattern sub(replstringcount )identical to the sub(functionusing the compiled pattern pattern subn(replstringcount )identical to the subn(functionusing the compiled pattern pattern pattern the pattern string from which the pattern object was compiled an example of using the compile(function is given below the pattern to be compiled is defined as containing or more digits ( to )import re line 'the price is containsintegers '\ +repattern re compile(containsintegersmatchline repattern search(line if matchline print('line contains number'elseprint('line does not contain number'the compiled pattern can then be used to apply methods such as search(to specific string (in this case held in line the output generated by this isline contains number |
19,291 | regular expressions in python of course the compiler pattern object supports range of methods in addition to search(as illustrated by the spilt methodp re compile( '\ +' ' high streetprint( split( )the output from this is [' ''high''street' online resources see the python standard library documentation forhow to the re module other online resources include start module that extends the functionality offered by the builtin re module exercises write python function to verify that given string only contains letters (upper case or lower caseand numbers thus spaces and underbars (' 'are not allowed an example of the use of this function might beprint(contains_only_characters_and_numbers('john')true print(contains_only_characters_and_numbers('john_hunt')false print(contains_only_characters_and_numbers(' ')true print(contains_only_characters_and_numbers('john ')true print(contains_only_characters_and_numbers('john ')false write function to verify uk postcode format (call it verify_postcodethe format of postcode is two letters followed by or numbersfollowed by |
19,292 | exercises spacefollowed by one or two numbers and finally two letters an example of postcode is sy zz another postcode might be bb po and finally we might have aa nn (note this is simplification of the uk postcode system but is suitable for our purposesusing the output from this function you should be able to run the following test codetrue print("verify_postcode('sy aa'):"verify_postcode('sy aa')true print("verify_postcode('sy zz'):"verify_postcode('sy zz')true print("verify_postcode('bb po'):"verify_postcode('bb po')false print("verify_postcode('aa nn '):"verify_postcode('aa nn ')true print("verify_postcode('aa nn'):"verify_postcode('aa nn')false print("verify_postcode('aa nn'):"verify_postcode('aa nn')false print("verify_postcode('aa nn'):"verify_postcode('aa nn')write function that will extract the value held between two strings or characters such as 'the function should take three parametersthe start characterthe end character and the string to process for examplethe following code snippetprint(extract_values('''')print(extract_values('''')print(extract_values('''')print(extract_values('''the was in the ')should generate output such as['john'[' '['john '['town''valley' |
19,293 | database access |
19,294 | introduction to databases introduction there are several different types of database system in common use today including object databasesnosql databases and (probably the most commonrelational databases this focusses on relational databases as typified by database systems such as oraclemicrosoft sql server and mysql the database we will use in this book is mysql what is databasea database is essentially way to store and retrieve data typicallythere is some form of query language used with the database to help select the information to retrieve such as sql or structured query language in most cases there is structure defined that is used to hold the data (although this is not true of the newer nosql or non-relational unstructured databases such as couchdb or mongodbin relational database the data is held in tableswhere the columns define the properties or attributes of the data and each row defines the actual values being heldfor example(cspringer nature switzerland ag huntadvanced guide to python programmingundergraduate topics in computer science |
19,295 | introduction to databases in this diagram there is table called studentsit is being used to hold information about students attending meeting the table has attributes (or columnsdefined for idnamesurnamesubject and email in this casethe id is probably what is known as primary key the primary key is property that is used to uniquely identify the student rowit cannot be omitted and must be unique (within the tableobviously names and subjects may well be duplicated as there may be more than one student studying animation or games and students may have the same first name or surname it is probable that the email column is also unique as students probably don' share an email address but again this may not necessarily be the case you might at this point wonder why the data in relational database is called relational and not tables or tabularthe reason is because of topic known as relational algebra that underpins relational database theory relational algebra takes its name from the mathematical concept known as relation howeverfor the purposes of this you don' need to worry about this and just need to remember that data is held in tables data relationships when the data held in one table has link or relationship to data held in another table then an index or key is used to link the values in one table to another this is illustrated below for table of addresses and table of people who live in that address this shows for examplethat 'phoebe gateslives at address 'addr which is queen streetbristolbs yy |
19,296 | what is database this is an example of many to one (often written as many: relationshipthat is there are many people who can live at one address (in the above adam smith also lives at address 'addr 'in relational databases there can be several different types of relationship such asone:one where only one row in one table references one and only one row in another table an example of one to one relationship might be from person to an order for unique piece of jewellery one:many this is the same as the above address examplehowever in this case the direction of the relationship is reversed (that is to say that one address in the addresses table can reference multiple persons in the people tablemany:many this is where many rows in one table may reference many rows in second table for examplemany students may take particular class and student may take many classes this relationship usually involves an intermediate (jointable to hold the associations between the rows the database schema the structure of relational database is defined using data definition language or data description language ( ddltypicallythe syntax of such language is limited to the semantics (meaningrequired to define the structure of the tables this structure is known as the database schema typicallythe ddl has commands such as create tabledrop table (to delete tableand alter table (to modify the structure of an existing tablemany tools provided with database allow you to define the structure of the database without getting too bound up in the syntax of the ddlhoweverit is useful to be aware of it and to understand that the database can be created in this way for examplewe will use the mysql database in this the mysql |
19,297 | introduction to databases workbench is tool that allows you to work with mysql databases to manage and query the data held within particular database instance for references for mysql and the mysql workbench see the links at the end of this as an examplewithin the mysql workbench we can create new table using menu option on databaseusing this we can interactively define the columns that will comprise the tablehere each column nameits type and whether it is the primary key (pk)not empty (or not null nnor unique (uqhave been specified when the changes are appliedthe tool also shows you the ddl that will be used to create the databasewhen this is applied new table is created in the database as shown below |
19,298 | what is database the tool also allows us to populate data into the tablethis is done by entering data into grid and hitting apply as shown below sql and databases we can now use query languages to identify and return data held in the database often using specific criteria for examplelet us say we want to return all the people who have the surname jones from the following tablewe can do this by specifying that data should be returned where the surname equals 'jones'in sql this would look likeselect from students where surname='jones'the above select statement states that all the properties (columns or attributesin row in the table students are to be returned where the surname equals 'jonesthe result is that two rows are returnednote we need to specify the table we are interested in and what data we want to return (the '*after the select indicated we want all the dataif we were only interested in their first names then we could useselect name from students where surname='jones' |
19,299 | introduction to databases this would return only the names of the students data manipulation language data can also be inserted into table or existing data in table can be updated this is done using the data manipulation language (dmlfor exampleto insert data into table we merely need to write an insert sql statement providing the values to be added and how they map to the columns in the tableinsert into 'students('id''name''surname''subject''email'values (' ''james''andrews''games''ja@my com')this would add the row to the table students with the result that the table would now have an additional rowupdating an existing row is little more complicated as it is first necessary to identify the row to be updated and then the data to modify thus an update statement includes where clause to ensure the correct row is modifiedupdate 'studentsset 'email'='grj@my comwhere 'id'=' 'the effect of this code is that the second row in the students table is modified with the new email address |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.