python-2.x

how to print directly to a text file in both python 2.x and 3.x?

十年热恋 提交于 2019-12-04 23:28:44
Instead of using write() , what are the other way to write to a text file in Python 2 and 3? file = open('filename.txt', 'w') file.write('some text') You can use the print_function future import to get the print() behaviour from python3 in python2: from __future__ import print_function with open('filename', 'w') as f: print('some text', file=f) If you do not want that function to append a linebreak at the end, add the end='' keyword argument to the print() call. However, consider using f.write('some text') as this is much clearer and does not require a __future__ import. f = open('filename.txt

Unexpected Behavior of itertools.groupby

这一生的挚爱 提交于 2019-12-04 22:55:04
问题 This is the observed behavior: In [4]: x = itertools.groupby(range(10), lambda x: True) In [5]: y = next(x) In [6]: next(x) --------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-6-5e4e57af3a97> in <module>() ----> 1 next(x) StopIteration: In [7]: y Out[7]: (True, <itertools._grouper at 0x10a672e80>) In [8]: list(y[1]) Out[8]: [9] The expected output of list(y[1]) is [0,1,2,3,4,5,6,7,8,9] What's going on here?

bytes vs bytearray in Python 2.6 and 3

与世无争的帅哥 提交于 2019-12-04 22:30:53
I'm experimenting with bytes vs bytearray in Python 2.6. I don't understand the reason for some differences. A bytes iterator returns strings: for i in bytes(b"hi"): print(type(i)) Gives: <type 'str'> <type 'str'> But a bytearray iterator returns int s: for i in bytearray(b"hi"): print(type(i)) Gives: <type 'int'> <type 'int'> Why the difference? I'd like to write code that will translate well into Python 3. So, is the situation the same in Python 3? mjv In Python 2.6 bytes is merely an alias for str . This "pseudo type" was introduced to [partially] prepare programs [and programmers!] to be

Buffers and Memoryview Objects explained for the non-C programmer

拜拜、爱过 提交于 2019-12-04 19:47:19
问题 Python 2.7 has introduced a new API for buffers and memoryview objects. I read the documentation on them and I think I got the basic concept (accessing the internal data of an object in a raw form without copying it, which I suppose means a "faster and less memory-hungry" way to get object data), but to really understand the documentation, the reader should have a knowledge of C that is beyond the one I have. I would be very grateful if somebody would take the time to: explain buffers and

Determining whether an value is a whole number in Python

╄→гoц情女王★ 提交于 2019-12-04 17:50:43
问题 I would like to determine if a numeric value in Python is a whole number. For example, given: y = x / 3 I want to distinguish between values of x which are evenly divisible by 3 those which are not. 回答1: if x % 3 == 0: print 'x is divisible by 3' 回答2: Integers have no decimals. If you meant "check if a number got decimals in Python", you can do: not float(your_number).is_integer() 回答3: Edit: As Ollie pointed out in the comment below this post, is_integer is part of the standard library and

Chunking bytes (not strings) in Python 2 and 3

可紊 提交于 2019-12-04 17:44:29
问题 This is turning out to be trickier than I expected. I have a byte string: data = b'abcdefghijklmnopqrstuvwxyz' I want to read this data in chunks of n bytes. Under Python 2, this is trivial using a minor modification to the grouper recipe from the itertools documentation: def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx args = [iter(iterable)] * n return (''.join(x) for x in izip_longest(fillvalue

How to manipulate the exception in __exit__ of a context manager?

浪尽此生 提交于 2019-12-04 11:35:45
问题 I know it's bad style to re-raise an exception from within a context manager's __exit__() method. So, I'd like to tack an attribute on the instance which can carry contextual information that isn't available if I let the exception trickle through or if I catch it. This will avoid re-raising it. The alternative to tacking the attribute on the exception would be to swallow the exception, set some state on the instance that doubles as the context manager in question and later check that state.

TypeErrors using metaclasses in conjunction with multiple inheritance

三世轮回 提交于 2019-12-04 10:01:01
I have two questions converning metaclasses and multiple inheritance. The first is: Why do I get a TypeError for the class Derived but not for Derived2 ? class Metaclass(type): pass class Klass(object): __metaclass__ = Metaclass #class Derived(object, Klass): pass # if I uncomment this, I get a TypeError class OtherClass(object): pass class Derived2(OtherClass, Klass): pass # I do not get a TypeError for this The exact error message is: TypeError: Error when calling the metaclass bases Cannot create a consistent method resolution order (MRO) for bases object, Klass The second question is: Why

How to force PyYAML to load strings as unicode objects?

浪子不回头ぞ 提交于 2019-12-04 09:54:33
问题 The PyYAML package loads unmarked strings as either unicode or str objects, depending on their content. I would like to use unicode objects throughout my program (and, unfortunately, can't switch to Python 3 just yet). Is there an easy way to force PyYAML to always strings load unicode objects? I do not want to clutter my YAML with !!python/unicode tags. # Encoding: UTF-8 import yaml menu= u"""--- - spam - eggs - bacon - crème brûlée - spam """ print yaml.load(menu) Output: ['spam', 'eggs',

Should I use “self” to define variables / objects of class instanced which I will not need to reach from the outside?

拥有回忆 提交于 2019-12-04 09:37:25
问题 I am not a complete beginner but fairly new to Python . Whilst working on a project today I just had an idea and wondered regarding the usage of " self "; about which I've been reading for the past some while and I still can not figure out if it's always necessary or not. My question solely concerns instances of classes and instance parameters/variables. This question is not about Class Variables which affect all instances . Example : class C: def __init__(self, parent = None): super(C, self)