You may optionally enter a comparison operator (<, <=, >, >=, <> or =) at the beginning of each of your search values to specify how the comparison should be done.
import os
searchPath = '/home/patrick/Desktop/'
# os.walk will go through all subdirectories
for pathentry in os.walk(searchPath, False):
for dir in pathentry[1]:
path = os.path.join(pathentry[0], dir)
if os.path.islink(path):
print path + "... is a link"
# os.unlink(path)
else:
print path + "... is a dir"
# os.rmdir(path)
for file in pathentry[2]:
path = os.path.join(pathentry[0], file)
# os.unlink(path)
print path + "... is a file"
# os.listdir only the given path
for file in os.listdir(searchPath):
fullfilename = os.path.join(searchPath, file)
if os.path.isfile(fullfilename):
print fullfilename + "... is a file"
76
Python
Netzwerk, Email
Email versenden
# Found at (and little modified): http://www.semi-legitimate.com/sls/blog/37-quick-notes/62-command-line-smtp-from-python
#!/usr/bin/python
import smtplib, sys
if len(sys.argv) != 5:
print "You must call me like:"
print " mailme from to subject msgfile"
sys.exit()
fromadr = sys.argv[1]
toadr = sys.argv[2]
subject = sys.argv[3]
msgfile = sys.argv[4]
try:
f = open(msgfile)
msg = f.read()
except:
print "Invalid Message File: " + msgfile
sys.exit()
m = "From: %s
To: %s
Subject: %s
X-Mailer: My-Mail
" \
% (fromadr, toadr, subject)
smtpserver="mysmtp.lan"
loginuser="Marty_McFly"
loginpwd="DeLorean"
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(loginuser, loginpwd)
smtp.ehlo()
smtp.sendmail(fromadr, toadr, m+msg)
smtp.close()
125
Python
Encoding / Decoding
Datei nach Base64 encodieren
myfile = 'myDoc.pdf'
ReturnValue = open(myfile).read().encode("base64")
# in ReturnValue ist nun der Base64-String
128
Python
Konsolenverwaltung
Einlesen Konsoleneingabe
yourname = raw_input('What\'s your name? ')
155
Python
Datum, Zeit
Aktuelles Datum/Uhrzeit
from datetime import date
iso_datum = date.today().isoformat()
output = iso_datum
print output
# 2013-12-05
# or
import datetime
datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
# 2013-12-05_18-09-10
159
Python
Textdateien
TextDatei auslesen
myFilename = "file.txt"
fileObj = open(myFilename , "r" )
array = []
for line in fileObj:
array.append( line )
fileObj.close()
160
Python
Exceptions
Try Catch Except
try:
print 1/0
except Exception as e:
print traceback.extract_stack()
else:
print "this is the else block"
finally:
print "finally clean up or something"
161
Python
Strings
String nach einem Teilstring durchsuchen
# http://www.tutorialspoint.com/python/string_find.htm
# this function is case sensitive
fullstring = "This is my string"
searchFor = "my"
startPosition = fullstring.find(searchFor, 0, len(fullstring))
# startPosition will have 8
if startPosition>=0:
print "I found it!"
startPosition = fullstring.upper().find(searchFor.upper()) # case insensitive