Įvestis / išvestis (I/O)

Skaitymas iš STDIN

# Skaitome iš STDIN
eilute = raw_input ('Ar taip? ');
if eilute in ('taip', 'Taip'):
	print "Jei taip, tai taip!"
	print "Turbut, kad ne... :-/"

str() ir repr()

The str() function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is not equivalent syntax). For objects which don't have a particular representation for human consumption, str() will return the same value as repr().

s = 'Hello, world.'
print str(s) # Hello, world.
print repr(s) # 'Hello, world.'
print str(0.1) # 0.1
print repr(0.1) # 0.10000000000000001
x = 10 * 3.25
y = 200 * 200
s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
print s # The value of x is 32.5, and y is 40000...

The repr() of a string adds string quotes and backslashes:

hello = 'hello, world\n'
hello_s = repr(hello)
print hello_s # 'hello, world\n'

The argument to repr() may be any Python object:

print repr((x, y, ('spam', 'eggs'))) # (32.5, 40000, ('spam', 'eggs'))

Reverse quotes are convenient in interactive sessions:

print `x, y, ('spam', 'eggs')` # (32.5, 40000, ('spam', 'eggs'))

repr() ir rjust() pavyzdys

Spausdiname skaičių kvadratų ir kubų lentelę:

for x in range(1, 11):
	print repr(x).rjust(2), repr(x*x).rjust(3),
	# Note trailing comma on previous line
	print repr(x*x*x).rjust(4)

This example demonstrates the rjust() method of string objects, which right-justifies a string in a field of a given width by padding it with spaces on the left. There are similar methods ljust() and center(). These methods do not write anything, they just return a new string. If the input string is too long, they don't truncate it, but return it unchanged; this will mess up your column lay-out but that's usually better than the alternative, which would be lying about a value. (If you really want truncation you can always add a slice operation, as in x.ljust(n)[:n].)

Kitas būdas padaryti tą patį

for x in range(1,11):
	print '%2d %3d %4d' % (x, x*x, x*x*x)

zfill() - užpildymas nuliais

Užpildome skaičiaus priekį nuliais:

print '12'.zfill (5) # 00012
print '-3.14'.zfill(7) # -003.14
print '3.14159265359'.zfill(5) # 3.14159265359

%, a la printf()

import math
print 'The value of PI is approximately %5.3f.' % math.pi # The value of PI is approximately 3.142.

If there is more than one format in the string, you need to pass a tuple as right operand, as in this example:

table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():
	print '%-10s ==> %10d' % (name, phone)
# Dcab       ==>       7678
# Jack       ==>       4098
# Sjoerd     ==>       4127

Using * to pass the width or precision in as a separate (integer) argument is supported. The C formats %n and %p are not supported.

If you have a really long format string that you don't want to split up, it would be nice if you could reference the variables to be formatted by name instead of by position. This can be done by using form %(name)format, as shown here:

table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table # Jack: 4098; Sjoerd: 4127; Dcab: 8637678


Atidarymas, uždarymas

Atidarome bylą skaitymui:

byla_1 = open ('/tmp/test1', 'r');

Atidarome bylą rašymui:

byla_2 = open ('/tmp/test2', 'w');

Atidarome bylą skaitymui ir rašymui:

byla_3 = open ('/tmp/test3', 'r+');

Atidarome binary bylą (reikalinga Windows ir Mac sistemoms):

byla_4 = open ('/tmp/test4', 'rb')

Uždarome bylas:



Skaitome VISĄ bylą:

byla = byla_1.read()

Skaitome vieną bylos eilutę:

eilute = byla_1.readline()

Pasidarome byloje esančių eilučių sąrašą:

eilutes = byla_1.readlines()
print eilutes # [ 'Pirma eilute.\n', 'Antra eilute.\n' ]

Skaitome visas eilutes (geresnis būdas):

for eilute in byla_1:
	print eilute,


Rašome eilutę į bylą (norint rašyti ką nors, kas nėra string'as, reikėtų panaudoti str()):

byla_2.write ('Labas, pasauli!\n')

Pozicija, jos keitimas

Sužinome poziciją byloje:

print byla_2.tell()

Nustatome poziciją į priekį:

byla_2.seek (0)


seek(offset, from_what)

from what parametras:

  • 0 - bylos pradžia (default)
  • 1 - dabartinė pozicija byloje
  • 2 - bylos pabaiga (offset'as turbūt bus neigiamas)


pickle išsaugo beveik bet ką eilutės formatu (kaip PHP'o serialize()):

import pickle
sarashas = [ 'Linas', 'Tomas', 'Kristijonas' ]
# Dump'iname
byla = open ('/tmp/test1', 'w')
pickle.dump (sarashas, byla)
del sarashas
# Load'iname
byla = open ('/tmp/test1', 'r')
sarashas = pickle.load (byla)
# Voila!
print sarashas
This website uses cookies for visitor traffic analysis. By using the website, you agree with storing the cookies on your computer.More information
Jei nenurodyta kitaip, šio wiki turinys ginamas tokia licencija: CC Attribution-Noncommercial-Share Alike 4.0 International
Recent changes RSS feed Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki