snippsat 661 Master Poster

Setuptool can be found here.
Correct environment variable is ;C:\python33\;C:\python33\scripts\;
Look that's is correct by looking at Path.

snippsat 661 Master Poster

Use PyUserInput
Install Pywin32 and Pyhook
Install pip
Then do pip install PyUserInput

from pykeyboard import PyKeyboard

k = PyKeyboard()    
# pressing a key
k.press_key('H')
# which you then follow with a release of the key
k.release_key('H')
Gribouillis commented: good idea +14
entropicII commented: This helpful so far but I have no idea how to use pip which probably sounds pretty stupid so please can you just tell me how to use pip +0
snippsat 661 Master Poster
In [34]:    
codeList = '''\
<ScanCode>
    <Code>Superman 12345</Code>
    <User>Clark kent</User>
    <DateTime></DateTime>
    <Comment/>
    <LineNumber></LineNumber>
    <SeqNumber></SeqNumber>
</ScanCode>'''

In [35]:    
import xml.etree.ElementTree as ET

In [37]:    
xml = ET.fromstring(codeList)

In [41]:    
xml.find('User').text
Out[41]:
'Clark kent'

In [42]:    
xml.find('Code').text
Out[42]:
'Superman 12345'
snippsat 661 Master Poster

the pring codelist prints out the cancodes/scancode/code section to show that it has fount something.

Is it in "xml" foramt?
Post a sample.

If i iterate over codelist(for el in codeList:),
like you do i can not use find() anymore.

In [25]:

for el in xml:
    print type(el)
    print el.attrib['key']
    print el.text        

<class 'xml.etree.ElementTree.Element'>
value
text
snippsat 661 Master Poster

Why lambda expression?
It can make code less readable.

All you should need to do is import string and apply in to your string's first character, and string.digits, and you should be able to use that as the lambda expression.

I agree,but there is no need to import string.
All string method are always available.
import string is only needed for make alfabet.

Just a test,and when the topic is lambda expression.

>>> print((lambda x: x[0].isdigit())('1hello'))
True
>>> print((lambda x: x[0].isdigit())('hello'))
False

>>> print((lambda x: x.startswith(('1','2','3')))('2hello'))
True
>>> print((lambda x: x.startswith(('1','2','3')))('3hello'))
True
>>> print((lambda x: x.startswith(('1','2','3')))('4hello'))
False

>>> import re
>>> print((lambda x: re.match(r'\d+', x))('987hello'))
<_sre.SRE_Match object at 0x02B01D40>
>>> print((lambda x: re.match(r'\d+', x))('hello'))
None

chophouse first you make a ordinary function,because that is eaiser.
Then if that dos not do it for you look into lambda expression or functools.partial
Or the more pythonic way as PyTony suggests.

Just one more,here a generator(yield).
Wish make code memory efficiency(only 1 line in memory).

def foo():
    with open('start_digit.txt') as f:
        for line in f:
            if line[0].isdigit():
                yield line.strip()

for line in foo():
    print line
Gribouillis commented: +1 for function foo() +14
snippsat 661 Master Poster
codeList = root.findall(".//ScanCodes/ScanCode/Code")
print codeList

What dos "print codelist" output.
So here as a demo i use find() to find "value" and "text"

in [1]:    
xml = '''\
    <foo>
       <bar key="value">text</bar>
    </foo>'''

In [2]:    
import xml.etree.ElementTree as ET

In [3]:    
xml = ET.fromstring(xml)

In [4]:    
xml.find('./bar').attrib['key']   
Out[4]:
'value'

In [5]:
xml.find('./bar').text    
Out[5]:
'text'
snippsat 661 Master Poster
snippsat 661 Master Poster

Post link and what you what out.

snippsat 661 Master Poster

That 100 line long fileBreak function is really not good at all.
You should split it up,functions should be around 10-15 lines.

Do not try to do to much in a single function.
Do a couple of task and have a clear return value.
This make code much eaiser to read and test.

snippsat 661 Master Poster

it does for the files but i jsut got told they arent files but subfolders that have the numbers in the names which makes this so much more confussing for me.

Use os.walk() it recursive scan all folder and subfolders.
Example.

import os
import re

search_pattern = r'\d'
target_path = os.path.abspath(".") #current folder
for path, dirs, files in os.walk(target_path):
    for folder_name in dirs:
        if re.findall(search_pattern, folder_name):
            print folder_name # Folder with numbers
            print(os.path.join(path, folder_name)) # Full path
snippsat 661 Master Poster

You really shouldn't be be using CGI.
Did you read me answer in you other post?

You never call calc function,line 18 i think should be inside calc function.
To get the error you get both listprice and discountpercent most be None.

>>> listprice = 100
>>> discountpercent = 80
>>> total = listprice - discountpercent
>>> total
20
>>> listprice = None
>>> discountpercent = None
>>> total = listprice - discountpercent
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'NoneType' and 'NoneType'
snippsat 661 Master Poster

The files I'm working on are all binary files, .mp3, .flac, & .wav. Does that help at all?

Sure you have to look at specification for these file types.
Like mp3 that use Id3 for metadata.
Search example "mp3 id3 character encoding".

Look at eyeD3
You see in source code that he really had to think about encoding.
Just one example.

property
    def text_delim(self):
        assert(self.encoding is not None)
        return b"\x00\x00" if self.encoding in (UTF_16_ENCODING,
                                                UTF_16BE_ENCODING) else b"\x00"

    def _initEncoding(self):
        assert(self.header.version and len(self.header.version) == 3)
        if self.encoding is not None:
            # Make sure the encoding is valid for this version
            if self.header.version[:2] < (2, 4):
                if self.header.version[0] == 1:
                    self.encoding = LATIN1_ENCODING
                else:
                    if self.encoding > UTF_16_ENCODING:
                        # v2.3 cannot do utf16 BE or utf8
                        self.encoding = UTF_16_ENCODING
        else:
            if self.header.version[:2] < (2, 4):
                if self.header.version[0] == 2:
                    self.encoding = UTF_16_ENCODING
                else:
                    self.encoding = LATIN1_ENCODING
            else:
                self.encoding = UTF_8_ENCODING

        assert(LATIN1_ENCODING <= self.encoding <= UTF_8_ENCODING)
snippsat 661 Master Poster

Yes is called default argument.

def say(msg, arg='something'):
    print 'first argument <{}> default argument <{}>'.format(msg, arg)

>>> say('hello')
first argument <hello> default argument <something>
>>> say('hello', 'world')
first argument <hello> default argument <world>

Many arguments.

def foo(*arg):
    return sum(arg)

>>> foo(1,2,3,4,5,6,7,8,9,10)
55  

Keyword arguments.

def bar(**kwargs):
    for key, value in kwargs.items():
        print '{}: {}'.format(key, value)

>>> bar(first_name='Clark kent', last_name='Superman')
first_name: Clark kent
last_name: Superman
snippsat 661 Master Poster

Cgi is pretty much dead in Python,and that's is very posetive.
Python community did make an all Python soution PEP 3333
So this is called WSGI(Web Server Gateway Interface),and is much better than cgi.
For small task like this is Flask and Bottle perfect.

snippsat 661 Master Poster

Stefan stop post your code in 8 years old Code Snippets post.
Yes Python has moved on,and your soultion is not better at all.

>>> from collections import Counter
>>> Counter('Her goes your text text'.lower().split())
Counter({'text': 2, 'goes': 1, 'her': 1, 'your': 1})
snippsat 661 Master Poster

Start by testing stuff out in interactive interpreter.

>>> lst = ['This', 'is' 'some', 'test', 'of', 'someting']
>>> lst[0]
'This'
>>> len(lst[0])
4

So useful for finding 4 letters word.
Basic iterate over a list.

>>> lst = ['This', 'is', 'some', 'test', 'of', 'someting']
>>> for item in lst:
...     print(item)
...     
This
is
some
test
of
someting

>>> for item in lst:
...     if len(item) == 4:     
...         print(item)
...         
This
some
test

>>> [item for item in lst if len(item) == 4]
['This', 'some', 'test']

Same for finding letter beginning "s" iterate over with startswith() method.
What "startswith" dos,the name pretty much reveale it.
help() works fine.

>>> help(str.startswith)
Help on method_descriptor:

startswith(...)
    S.startswith(prefix[, start[, end]]) -> bool

    Return True if S starts with the specified prefix, False otherwise.
    With optional start, test S beginning at that position.
    With optional end, stop comparing S at that position.
    prefix can also be a tuple of strings to try.
snippsat 661 Master Poster

Re upload your code with working indentation.

timetraveller1992 commented: good call. esp since it's python! +0
snippsat 661 Master Poster

Do you mean download a file in chunk(spilt it up) so it dos not use so much memory?
Something like a do in this post.

snippsat 661 Master Poster

I think Gribouillis has postet some about unicode in Python 3 in your previous posts.
Can take a little more about this,for unicode was a big change in Python 3.

If you get a UnicodeDecodeError
it most likely means that you’re not reading the file in the correct encoding.
You should carefully read the specification of whatever it is that you’re reading and check that you’re doing it right (e.g., reading data as UTF-8 instead of Latin-1 or whatever it needs to be)
Python 3 is much more picky than Python 2,because of changes made to unicode.

Example in interactive shell all will be ok,we are not reading from file and unicode is great.

Python 3.4
>>> print('Spicy jalapeño ☂')
Spicy jalapeño ☂

Pyhon 2.7
>>> print('Spicy jalapeño ☂')
Spicy jalapeño ☂

Save Spicy jalapeño ☂ as jala.txt and read() it.

>>> f = open('jala.txt', 'rt', encoding='utf-8')
>>> print(f.read())
Traceback (most recent call last):
  File "<pyshell#53>", line 1, in <module>
    print(f.read())
  File "C:\Python34\lib\codecs.py", line 313, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf1 in position 12: invalid continuation byte

So in test i saved Spicy jalapeño ☂ with cp1252 encoding.
When i try to read it with 'utf-8' i get error.

>>> f = open('jala.txt', 'rt', encoding='cp1252')
>>> print(f.read())
Spicy jalapeño ?

It almost work,but it's not correct for umbrella.

Save Spicy jalapeño ☂ with utf-8 encoding.

>>> f = open('jala.txt', …
snippsat 661 Master Poster

And there you go, you just mentioned another way of solving the problem. There are several ways to the market in this case.

Yes there are severals ways,i was also thinking about regex,but split and startswith works just fine in this simple case.
And may even be better than regex because Readability counts.

>>> s = '20140702_PAQT_B6h'
>>> r = re.search(r'_(P.*)_(B.*)', s)
>>> r.group(1)
'PAQT'
>>> r.group(2)
'B6h'

Perl has There's more than one way to do it (TMTOWTDI)

I think Python's

There should be one-- and preferably only one --obvious way to do it.

Can always be debated,but i think soultion postet here work fine,and to debated about(obvious way) has no point in this case.

snippsat 661 Master Poster

pyinstaller to make an executable, wouldn't that eliminate the need for the python to be installed on the system?

Yes and there are more tool,a GUI tool for many freezing tool.

Nukita and also Cython can make "exe",a new approach pynsist
See video from pycon 2014, The Day of the EXE Is Upon Us conclusion at end of video.

If you search for cx_Freeze(work Linux and Windows) and py2exe(now also work Python 3) on Daniweb you find working code.
Innosetup as mention by Hiroshe is my favorite tool for make installer,fine to use after freezing tool to get a nice installer.

For my project wx_nrk(Downloading norwegian Tv)
Has some user ca2000,for Windows i used Py2exe and for Linux no packing tool just a readme with install instruction(easier for Linux user because Python is pre-installed).

snippsat 661 Master Poster

and now please tell me the default path, that the command codecs.open() makes use of. or tell me the path of the file u saved in.. )

codecs.open() dos not use a path,you can give a path if you are not running .py in same folder as as ihij.txt.
If run .py in same folder as i did in with my test_hindi.txt i do not need to specify a path.

the file has hardly 25 words, then how can the word be repeated 172 times..

I get a count of 172(पर) with ihij.txt,wish seems correct to me.
Why do you think it's wrong?

snippsat 661 Master Poster

I get a count of 4 with conted in your last post,i save your content as UTF-8 and read it in same way.

#Python 2.7 
import codecs

with codecs.open('test_hindi.txt', encoding='utf-8') as f:
    contend = f.read()

word_cont = contend.count(u'\u092a\u0930')
print contend
print '-' * 30
print repr(contend)
print '-' * 30
print word_cont

'''Output-->
इस पृष्ठ पर इन्टरनेट पर उपलब्ध विभिन्न हिन्दी एवं देवनागरी सम्बंधित साधनों की कड़ियों की सूची है। इसमें ऑनलाइन एवं ऑफ़लाइन उपकरण शामिल हैं। इस पृष्ठ पर इन्टरनेट पर उपलब्ध विभिन्न हिन्दी एवं देवनागरी सम्बंधित साधनों की कड़ियों की सूची है। इसमें ऑनलाइन एवं ऑफ़लाइन उपकरण शामिल हैं।
------------------------------
u'\ufeff\u0907\u0938 \u092a\u0943\u0937\u094d\u0920 \u092a\u0930 \u0907\u0928\u094d\u091f\u0930\u0928\u0947\u091f \u092a\u0930 \u0909\u092a\u0932\u092c\u094d\u0927 \u0935\u093f\u092d\u093f\u0928\u094d\u0928 \u0939\u093f\u0928\u094d\u0926\u0940 \u090f\u0935\u0902 \u0926\u0947\u0935\u0928\u093e\u0917\u0930\u0940 \u0938\u092e\u094d\u092c\u0902\u0927\u093f\u0924 \u0938\u093e\u0927\u0928\u094b\u0902 \u0915\u0940 \u0915\u0921\u093c\u093f\u092f\u094b\u0902 \u0915\u0940 \u0938\u0942\u091a\u0940 \u0939\u0948\u0964 \u0907\u0938\u092e\u0947\u0902 \u0911\u0928\u0932\u093e\u0907\u0928 \u090f\u0935\u0902 \u0911\u092b\u093c\u0932\u093e\u0907\u0928 \u0909\u092a\u0915\u0930\u0923 \u0936\u093e\u092e\u093f\u0932 \u0939\u0948\u0902\u0964 \u0907\u0938 \u092a\u0943\u0937\u094d\u0920 \u092a\u0930 \u0907\u0928\u094d\u091f\u0930\u0928\u0947\u091f \u092a\u0930 \u0909\u092a\u0932\u092c\u094d\u0927 \u0935\u093f\u092d\u093f\u0928\u094d\u0928 \u0939\u093f\u0928\u094d\u0926\u0940 \u090f\u0935\u0902 \u0926\u0947\u0935\u0928\u093e\u0917\u0930\u0940 \u0938\u092e\u094d\u092c\u0902\u0927\u093f\u0924 \u0938\u093e\u0927\u0928\u094b\u0902 \u0915\u0940 \u0915\u0921\u093c\u093f\u092f\u094b\u0902 \u0915\u0940 \u0938\u0942\u091a\u0940 \u0939\u0948\u0964 \u0907\u0938\u092e\u0947\u0902 \u0911\u0928\u0932\u093e\u0907\u0928 \u090f\u0935\u0902 \u0911\u092b\u093c\u0932\u093e\u0907\u0928 \u0909\u092a\u0915\u0930\u0923 \u0936\u093e\u092e\u093f\u0932 \u0939\u0948\u0902\u0964'
------------------------------
4
'''
snippsat 661 Master Poster

Import is.

>>> import xml.etree.ElementTree as ET
>>> ET.VERSION
'1.3.0'

And you should not name file elementtree.py,it shall not be in desktop folder.
This is a file in Pyhon library.

For me only Beautiful Soup or lxml for parsing.

snippsat 661 Master Poster

Hey ... sorry I missed that ... is that why you 'down-voted' ?

It was not me as downvoted you :)

snippsat 661 Master Poster

The error message is very clear,Python can not find "sample.txt" in that path.

with open('C:/Users/jolie_tia/Documents/sample.txt') as f:
    print f.name

'''Output-->
Message File Name   Line    Position
    Traceback
<module> <module4>    1
IOError: [Errno 2] No such file or directory:                               'C:/Users/jolie_tia/Documents/sample.txt'
'''

Here i fixing the error by making folders for that path and put "sample.txt" in Documents folder.

with open('C:/Users/jolie_tia/Documents/sample.txt') as f:
    print f.name

'''Output-->
C:/Users/jolie_tia/Documents/sample.txt
'''

Check your path to file again,cd to folder in Linux(terminal) an open sample.txt.
I guess you use Linux because you have not specified a drive letter.
If you use Windows,you do of course need to specifi a drive letter as i do.

Dont use file as a variable name,file is a reserved word used bye Python.

snippsat 661 Master Poster

You have convert all input to integers,so answer(ans) is also an integer.
Can look at some improvement.

num1 = int(raw_input("Enter an integer"))
num2 = int(raw_input("Enter a second integer"))
num3 = int(raw_input("Enter a third integer"))
print "The sum of the 3 integers entered is: {}".format(sum((num1, num2, num3)))

So in this version use build in sum() and string formatting.

>>> a = 1, 2, 3
>>> a
(1, 2, 3)
>>> sum(a)
6
>>> print '{} {}'.format('my score is' , sum(a))
my score is 6

If you think of it,it's really the same answer repeating 3 times.

result = []
for times in range(3):
    result.append(int(raw_input("Enter an integer: ")))
print "The sum of the 3 integers entered is: {}".format(sum(result))
ddanbe commented: Super! +15
snippsat 661 Master Poster
def lst_corrector(lst, index_vaule):
    value_change = raw_input('Enter correct value: ')
    for index, item in enumerate(lst):
        if index == index_to_change:
            lst[index] = value_change
            return lst

#Error should be car
lst = ['boat', 'train', 'carfd']
index_to_change = 2
print lst_corrector(lst, index_to_change)
#--> ['boat', 'train', 'car']
snippsat 661 Master Poster

Dont use list and dict as variable names,words are reseverd bye Python.
To clean it up.

my_file = open("words.txt")
lst = [] #Outside the loop
for word in my_file:
    word = word.strip()
    lst.append(word)
my_file.close()

#searching for the word in list
search_word = "fox"
if search_word in lst:
    print 'Word found: <{}>\nDictionary {}'.format(search_word, lst)
else:
    print "You typed a word that dosen't exist"

'''Output-->
Word found: <fox>
Dictionary ['bear', 'wolf', 'fox']
'''

Don't place all code in one big function.
Do some execerice on function,and try to keep function small and do a specific task and return result out.
This make code eaiser to read an test.

def read_contend(dictionary):
    '''Read contend and return a list'''
    with open(dictionary) as f_obj:
        word_lst = [word.strip() for word in f_obj]
        return word_lst

def search_contend(search_word, word_lst):
    '''Search for a word in input contendt'''
    if search_word in word_lst:
        return search_word
    return "You typed a word that dosen't exist"

if __name__ == '__main__':
    dictionary = 'words.txt'
    search_word = "fox"
    word_lst = read_contend(dictionary)
    print search_contend(search_word, word_lst)
snippsat 661 Master Poster

Slice it out can be another option.

with open('06 Rooster.mp3', 'rb') as f:
    f.seek(-128,2)
    tag_content = f.read(128)
    title = tag_content[3:33]
    print title # Rooster

You do know that there are several libraries that can do this(Mutagen,eyeD3...)?

import eyed3

audiofile = eyed3.load("06 Rooster.mp3")
print audiofile.tag.title
print audiofile.tag.artist
print audiofile.info.bit_rate_str

'''Output-->
Rooster
Alice In Chains
~195 kb/s
'''

Your other post.
http://www.daniweb.com/software-development/python/threads/479773/mp3-meta-data

snippsat 661 Master Poster

by having a capturing group ([a-z]), I still got 175 matches and they were just single letters

Did you place [^A-Z] as i told you?
Then it should look like this [^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]

snippsat 661 Master Poster

I have tried a written a code like so re.findall(r'[A-Z]{3}[a-z][A-Z]{3}',string) to find the solution for this python challenge

Add [^A-Z] in each end.

[^A-Z] # any character except a capital letter
[^A-Z] # ensures that there isn't a 4th uppercase letter

And parentes () around [a-z],so it's a capturing group.
This is capturing group 1 with re.findall().
You don't specific group call like you do with re.search().
re.findall() just return output from capturing group 1.

>>> import re
>>> s = 'Python is fun'
>>> re.findall(r'\w.*(fun)', s)
['fun']
>>> re.search(r'\w.*(fun)', s).group(0) #or just .group()
'Python is fun'
>>> re.search(r'\w.*(fun)', s).group(1)
'fun'
snippsat 661 Master Poster

Take a look at Click from the creator of Flask Armin Ronacher.

Gribouillis commented: Very interesting! +14
snippsat 661 Master Poster

Hint.

>>> import re
>>> data = '''(*^+*]$]+@+*_##)&)^(@$^]e@][#&)('''
>>> re.findall(r'[a-z]', data)
['e']
snippsat 661 Master Poster

Here a version of iglob,that can take multiple file extensions.

#iter_glob
from glob import iglob
from itertools import chain
import os, sys

def iter_glob(path=None, *args):
    '''A iglob version that return an iterator fully lazy evaluated
     and can handle multiple file extensions.
    #--- Usage ---#
    from iter_glob import iter_glob
    for filename in multi_glob(folder_path, '*.py', '*.txt'):
        print filename
    '''
    try:
        os.chdir(path)
    except Exception as error:
        print 'Wrong folder path {},try again'\
        .format(str(error).split(':',1)[-1].strip())
        sys.exit()
    return chain.from_iterable(iglob(pattern) for pattern in args)

Test:

>>> from iter_glob import  iter_glob
>>> for filename in iter_glob(r'C:\temp', '*.py', '*.txt'):
...     print filename
...     
micc.py
module9.py
tid_delta_csv.py
pass.txt
VRayLog.txt

>>> for filename in iter_glob(r'C:\temp999', '*.py', '*.txt'):
...     print filename
...     
Wrong folder path 'C:\\temp999',try again
snippsat 661 Master Poster

This is a no-op :)

Yes i can agree with that :)

#multi_glob.py
from glob import glob
import os

def multi_glob(path=None, *args):
    '''glob that can handle multiple file extensions option.
    #--- Usage ---#
    from multi_glob import multi_glob
    multi_glob(folder_path, '*.py', '*.txt')
    '''
    try:
        os.chdir(path)
    except OSError:
        return 'Wrong folder path,try again'
    f_lst = []
    for files in args:
        f_lst.extend(glob(files))
    return f_lst

Test:

>>> from multi_glob import multi_glob
>>> print multi_glob(r'C:\temp', '*.py', '*.txt')
['micc.py', 'module9.py', 'tid_delta_csv.py', 'pass.txt', 'VRayLog.txt']
>>> print multi_glob(r'C:\temp999', '*.py', '*.txt')
Wrong folder path,try again
snippsat 661 Master Poster

I give it a try for fun.

#multi_glob.py
from glob import glob
import os

def multi_glob(path=None, *args):
    '''glob that can handle multiple file extensions option.
    #--- Usage ---#
    from multi_glob import multi_glob
    multi_glob(folder_path, '*.py', '*.txt')
    '''
    try:
        os.chdir(path)
    except OSError:
        os.chdir(os.getcwd())
        print 'Wrong path using script(.py) folder path'
    f_lst = []
    for files in args:
        f_lst.extend(glob(files))
    return f_lst

Test:

>>> from multi_glob import multi_glob
>>> print multi_glob(r'C:\temp999', '*.py', '*.txt')
Wrong path using script(.py) folder path
['02252014-162200.709116.txt', 'saladsfilecost.txt']

>>> print multi_glob(r'C:\temp', '*.py', '*.txt')
['micc.py', 'module9.py', 'tid_delta_csv.py', 'pass.txt', 'VRayLog.txt']

>>> help(multi_glob)
Help on function multi_glob in module __main__:

multi_glob(path=None, *args)
    glob that can handle multiple file extensions option.
    #--- Usage ---#
    from multi_glob import multi_glob
    multi_glob(folder_path, '*.py', '*.txt')
snippsat 661 Master Poster

Is wxPython still around?

Yes still alive.
Lastet officale oppdate is(25-Dec-2013) wxPython (classic) 3.0.0.0

It will soon be ready for Python 3,work is going on Project Phoenix
Work well for Python 3,to test it out look here

snippsat 661 Master Poster

One way.

f_object = open('filename', 'rb')
while True:
    chunk = f_object.read(180)
    if not chunk: break
    do_something_with(chunk)
f_object.close()

More modern an pythonic.

from functools import partial

with open('filename', 'rb') as f_object:
    for byte in iter(partial(f_object.read, 180), b''):
        # Do stuff with byte
Gribouillis commented: interesting +14
snippsat 661 Master Poster

Same after "d" missing comma.
Learn to use string formatting.

>>> a = 100
>>> difference = 'high'
>>> print('The gap between {} and 1000000 is {}'.format(a, difference))
The gap between 100 and 1000000 is high

http://ebeab.com/2012/10/10/python-string-format/

A good Python editor will spot error like this for you.
Pycharm has now a Free Community Edition,that's good.

snippsat 661 Master Poster

I was thinking that if a <title> has no corresponding <pos>, delete that title, but I don't know how to do that. Can anyone suggest a solution?

Some hint use fetchNextSiblings() if return empty list,then decompose() that title tag.

xml = '''\
<page>
<title>dasher</title>
<pos>red</pos>
</page>
<page>
<title>dancer</title>
<pos>red</pos>
<pos>blue</pos>
</page>
<page>
<title>coconut</title>
</page>
<page>
<title>rudolph</title>
<pos>red</pos>
<pos>brown</pos>
<pos>red</pos>
</page>'''


from bs4 import BeautifulSoup

soup = BeautifulSoup(xml)
title = soup.find_all('title')

for index, item in enumerate(title):
    print index, item  
'''
0 <title>dasher</title>
1 <title>dancer</title>
2 <title>coconut</title>
3 <title>rudolph</title>
'''

for index, item in enumerate(title):
    print index, item.fetchNextSiblings() 
'''
0 [<pos>red</pos>]
1 [<pos>red</pos>, <pos>blue</pos>]
2 []
3 [<pos>red</pos>, <pos>brown</pos>, <pos>red</pos>]
'''

for index, item in enumerate(title):
    if item.fetchNextSiblings() == []:
        print item.decompose()
'''None'''

for index, item in enumerate(title):
    print index, item  
'''
0 <title>dasher</title>
1 <title>dancer</title>
2 <None></None>
3 <title>rudolph</title>
'''
snippsat 661 Master Poster

Good effort Peter 18,the code dos what it shall.
I would suggest some improvements.
To strip off \n is better to use strip()

>>> s = 'hello\n'
>>> s.strip()
'hello'

So code under can be one line matchf = [i.strip() for i in dllmatch]

matchf = dllmatch.readlines()

for i in range(0,len(matchf)):
    if matchf[i][-1] == "\n":
        matchf[i] = matchf[i][:-1]    # :-1 to strip off \

Complete code with a couple more changes.

import os
import shutil    

source = os.listdir("C:\\Windows\\System32")
destination = "C:\\Tools"  

with open('my_file.txt') as f_obj:
    matchf = [i.strip() for i in f_obj]

for files in source:
    if files.endswith('.dll') and files in matchf:
        shutil.copy(os.path.join(sourcedir, files), destination)
snippsat 661 Master Poster

Do I need to use .format?

Maybe this help.

>>> lst = ['$10.00', '$8.00', '$10.00', '$6.00', '$10.00', '$10.00']
>>> new_lst = [float(i.split('$')[1]) for i in lst]
>>> new_lst
[10.0, 8.0, 10.0, 6.0, 10.0, 10.0]
>>> total = sum(new_lst)
>>> total
54.0
>>>
>>> print('Sum of lst is ${}'.format(total))
Sum of lst is $54.0
>>>
>>> print('The sum of this list: {} is ${}'.format(lst, total))
The sum of this list: ['$10.00', '$8.00', '$10.00', '$6.00', '$10.00', '$10.00'] is $54.0
snippsat 661 Master Poster

Not sure if this will help me but....This is the file: This how the program writes the $10.00 too the file.

What to you want,sum up all number as you postet before?
Show exact output you want.

how does it work without "C:\number.txt"mine won't woek without the C:\ part

Running code(.py) in same folder as number.txt,then no path is needed.
Never use single \ in filename "C:\number.txt" wrong.
C:\\number.txt ok, r"C:\number.txt" raw string ok,or "C:/number.txt".

snippsat 661 Master Poster
import os
import xml.etree.ElementTree as ET

tree = ET.parse("test.xml")
root = tree.getroot()
for element in root.iter('Path'):
    print os.path.basename(element.text)

'''Output-->
Riched32.dll
napinsp.dll
test.exe
'''

Fix so "exe" not is in output.

import os
import xml.etree.ElementTree as ET

tree = ET.parse("test.xml")
root = tree.getroot()
for element in root.iter('Path'):
    file_name = os.path.basename(element.text)
    #jpg just an example that you can have more values
    if not file_name.endswith(('.exe', '.jpg')): 
        print file_name

'''Output-->
Riched32.dll
napinsp.dll
'''
snippsat 661 Master Poster

and this is the file:

Running fine for me in both my code example,and i run code in Python 3.

#Python 3
totals = open('number.txt') #just copy,paste and save to number.txt.
number_lst = []
for line in totals:
    line = line.strip().split('$')
    number_lst.append(float(line[1]))

print(number_lst) #[10.0, 8.0, 10.0, 6.0, 10.0, 10.0]
print(sum(number_lst)) #54.0
totals.close()
snippsat 661 Master Poster

I got this error:

My number.txt is just a copy from your first post.

$10.00 
$10.00 
$10.00 
$10.00 
$10.00 
$10.00 

this is the code I used:

You have changes indentation by moving print lines,please do not change code when you test.
Indentation in Python is very important.

also i forgot to mention each time I run the program a new amount is added to the file like this:

The format is the the same,so it should work and sum up as i showed.

snippsat 661 Master Poster

You don't know that print element.text just was an example?
A simple test and you should be able to figure very basic stuff like this out.
You just use os.path.basename(element.text)

import os
import xml.etree.ElementTree as ET

f_out = open('my_file.txt', 'w')
tree = ET.parse("test.xml")
root = tree.getroot()
for element in root.iter('Path'):
    f_out.write('{}\n'.format(os.path.basename(element.text)))
f_out.close()
snippsat 661 Master Poster

print [float(i.split('$')[1])#########for i in lst]
I got a syntax error where I put the #######

In Python 3 print is a function so you need ().

#Python 3
with open('number.txt') as f:
    lst = [i.strip() for i in f]
    print(lst)
    print([float(i.split('$')[1]) for i in lst]) #split out $ and make float
    print(sum(float(i.split('$')[1]) for i in lst)) #sum upp all numbers

I am not sure what the first line of code

with open() is the prefered way to use.
It dos some cleaing up and close file object for you.

can you help me doing the same thing using the code below?
also in my version

totals = open('number.txt')
total_lst = totals.readlines() #readlines not readline
print(total_lst)

for line in total_lst:
    print(line)
totals.close()

Next split() and make float and sum up.

totals = open('number.txt')
total_lst = totals.readlines() 
number_lst = []
for line in total_lst:
    line = line.strip().split('$')
    number_lst.append(float(line[1]))

print(number_lst) #[10.0, 10.0, 10.0, 10.0, 10.0, 10.0]
print(sum(number_lst)) #60.0
totals.close()

Or try this,just iterate over file object and see what you get.
So really no need for readlines() at all,in my example or your's.

totals = open('number.txt')
for line in totals:
    print(line.strip())
snippsat 661 Master Poster

Some hint,using a parser in standard library ElementTree.
Most of the time i use BeautifulSoup or lxml for parsing.

import os
import xml.etree.ElementTree as ET

tree = ET.parse("test.xml")
root = tree.getroot()
for element in root.iter('Path'):
    print element.text
    print os.path.basename(element.text)

'''Output-->
C:\Windows\system32\Riched32.dll
Riched32.dll
C:\Windows\system32\napinsp.dll
napinsp.dll
'''

But not duplicated .dll words

Use set()

and my .csv file

Try to do something yourself,post code if stuck.