os.path – is een module om de pad te manipuleren.
exists(path) # Test for existence
isabs(path) # Return 1 if path is an absolute pathname
isfile(path) # Return 1 if path is a regular file
isdir(path) # Return 1 if path is a directory
islink(path) # Return 1 if path is a symlink
ismount(path) # Return 1 if path is a […]
Archive for the ‘Python’ Category
Python path file exists
Python file path
os.path – is een module om de pad te manipuleren.
os.path methods:
abspath(path) # Returns the absolute pathname of a path
basename(path) # Returns filename component of path
dirname(path) # Returns directory component of path
normcase(path) # Normalize capitalization of a name
normpath(path) # Normalize a pathname
split(path) # Split path into (directory, file)
splitdrive(path) # Split path into (drive, pathname)
splitext(path) # […]
Standard Input, Output, and Error
sys.stdin - Standard input
sys.stdout - Standard output
sys.stderr - Standard error
Ingebouwde functies:
print outputs to sys.stdout
input() and raw_input() read from sys.stdin
Voorbeeld:
s = raw_input(”type a command : “)
print “You typed “, s
alle standaard foutmeldingen worden naar sys.stderr verzonden.
Het is mogelijk om sys.stdout te vervangen.
Voorbeeld:
import sys
sys.stdout = open(“output.txt”, “w”)
informatie zal nu in bestand geschreven worden.
Python File Eigenschappen
Iedere object van het bestaand (file) heeft volgende eigenschappen.
f.closed # Set to 1 if file object has been closed
f.mode # I/O mode of the file
f.name # Name of file if created using open(). # Otherwise, a string indicating the source
f.softspace # Boolean indicating if extra space needs to be
# printed before another value when […]
Python unicode
Python Unicode Tutorial
This is brief tutorial aimed at explaining the Unicode additions to Python. Please help me keep it up to date and accurate!
Why is Python getting Unicode support?
Once you get beyond the ASCII world, there are many different native encodings for different languages and operating systems.
Python File Methods
De volgende methods kunnen toegepast worden op een file object:
f.read([n]) # Read at most n bytes
f.readline([n]) # Read a line of input with max length of n
f.readlines() # Read all input and return a list of lines
f.write(s) # Write string s
f.writelines(ls) # Write a list of strings
f.close() # Close a file
f.tell() # Return current file […]
Python File Objects
open(filenam[, mode]) – om een bestand te openen. Standaard wordt een bestand geopend om te lezen. Mogelijke modes zijn er:
"r" Open for reading
"w" Open for writing (truncating to zero length)
"a" Open for append
"r+" Open for read/write (updates)
"w+" Open for read/write (with truncation to zero length)
A ’b’ may be appended to the mode to indicate binary […]
Python re
Met module “re” kan een string verwerkt worden volgens een bepaalde pattern. Meestal wordt het gebruikt om mix van tekst en speciale tekens te zoeken.
. Matches any character except newline by default
^ Matches the start of the string
$ Matches the end of the string
* "Any number of occurrences of what just preceded me"
+ "One or […]
Python tekst verwerking
Er zijn functies om tekst te verwerken.
string.atof(s) # Convert to float
string.atoi(s) # Convert to integer
string.atol(s) # Convert to long
string.count(s,pattern) # Count occurrences of pattern in s
string.find(s,pattern) # Find pattern in s
string.split(s, sep) # String a string
string.join(strlist, sep) # Join a list of string
string.replace(s,old,new) # Replace occurrences of old with new
s = "Hello World"
a = string.split(s) […]
Python Library bibliotheek
Python is verdeeld in standaard modules:
String processing
Operating system interfaces
Networking
Threads
GUI
Database
Language services
Security.
Er zijn ook vele bibliotheken van derden
XML
Numeric Processing
Plotting/Graphics
ezv.
Alle bibliotheken zijn toegankelijk met “import”
import string
…
a = string.split(x)
Popular Python Tools and Extensions
Domain - Extensions
Systems programming - Sockets, threads, signals, pipes, RPC calls, POSIX bindings
Graphical user interfaces - Tk, PMW, MFC, X11, wxPython, KDE, Gnome
Database interfaces - Oracle, Sybase, […]
Python Modules
Grotte programma's zou kunnen verdeeld worden in modules.
# numbers.py
def divide(a,b):
q = a/b
r = a - q*b
return q,r
def gcd(x,y):
g = y
while x > 0:
g = x
x = y % x
y = g
return g
#run.py
import numbers
x,y = numbers.divide(42,5)
n = numbers.gcd(7291823, 5683)
Python Files
f = open("foo","w") # Open a file for writing
g = open("bar","r") # Open a file for reading
f.write("Hello World")
data = g.read() # Read all data
line = g.readline() # Read a single line
lines = g.readlines() # Read data as a list of lines
of
f = open('read.txt', 'w+t') # Create a files
for i in range(3):
f.write('Line #%d\n' % i)
f.seek(0)
f.read(3) # […]
Python Exceptions
Fout die zou kunnen gebeuren afhandelen.
try:
f = open("foo")
except IOError:
print "Couldn’t open ’foo’. Sorry."
def factorial(n):
if n < 0:
raise ValueError,"Expected non-negative number"
if (n <= 1): return 1
else: return n*factorial(n-1)
Instantie doorgeven of standaard sys.exc_info afdrukken:
try:
parser.feed(self.content)
except sgmllib.SGMLParseError, inst:
self.error = inst
return 0
except UnicodeEncodeError, inst:
self.error = inst
return 0
except:
self.error = sys.exc_info()[0]
Uncaught exception
>>> factorial(-1)
Traceback (innermost […]
Python Classes
Declaratie:
class Account:
def __init__(self, initial):
self.balance = initial
def deposit(self, amt):
self.balance = self.balance + amt
def withdraw(self,amt):
self.balance = self.balance - amt
def getbalance(self):
return self.balance
Gebruik:
a = Account(1000.00)
a.deposit(550.23)
a.deposit(100)
a.withdraw(50)
print a.getbalance()
Python Functions
# Return the remainder of a/b
def remainder(a,b):
q = a/b
r = a - q*b
return r
# Now use it
a = remainder(42,5) # a = 2
Het is mogelijk om meerdere values te doorgeven:
def divide(a,b):
q = a/b
r = a - q*b
return q,r
x,y = divide(42,5) # x = 8, y = 2
Python for
for i in [3, 4, 10, 25]:
print i
# Print characters one at a time
for c in "Hello World":
print c
# Loop over a range of numbers
for i in range(0,100):
print i
Python while
n = 12
i = 1
while i<=12:
print i,"x 8 =", i*8
i=i+1
print "hello world"
while true:
pass # loop die niets doet.
Python Loops
while a < b:
# Do something
a = a + 1
directory doorbladeren:
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
… print k, v
…
gallahad the pure
robin the brave
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
… print i, v
…
0 tic
1 tac
2 toe
tuple doorbladeren:
for i in f:
print i
for i in […]
Python Dictionary Access
u = c[’uid’] # Get an element
c[’shell’] = "/bin/sh" # Set an element
if c.has_key("directory"): # Check for presence of an member
d = c[’directory’]
else:
d = None
d = c.get("directory",None) # Same thing, more […]
Python Dictionaries - Associative Arrays
a = { }
Leeg dictionary
b = { ’x’: 3, ’y’: 4 }
dictionary b bevat 3 met key ‘x’ en 4 met key ‘y’
c = { ’uid’: 105,
’login’: ’beazley’,
’name’ : ’David Beazley’
}
dictionary kan verschillende datatypes bevatten.
