środa, 2 października 2013

Playing with files in python

#!/usr/bin/python
import time
def line():
    print "-" *50
 
start = time.time()
try:
    print "check stats of the file\n"
    file = open("/tmp/file.dat")
    print "name of the file is: ",file.name
    print "closed or not", file.closed
    print "opening mode :", file.mode
    print "softspace flag: ",file.softspace

except IOError as e:
    print "I/O Error({0} : {1}) ".format(e.errno, e.strerror)
line()
try:
    print "insert var value to file\n"
    fo = open("/tmp/file.dat")
    print "the name of the file is: ", fo.name
    print "closing mode: ", fo.mode
    fo.close()
except IOError as e:
    print "I/O Error({0} : {1}) ".format(e.errno, e.strerror)
 

line()
print "write to file\n"
try:
    file = open("/tmp/file.dat","wb")
    file.write("Marek Borkowski")
    file.close()
except IOError as e:
    print "I/O Error({0} : {1}) ".format(e.errno, e.strerror)
 
 
line()
try:
    file = open("/tmp/file.dat","r+")
    str = file.read();
    print "Read String from file:", file, " \nis\n", str
    file.close()
 
except IOError as e:
    print "I/O Error({0} : {1}) ".format(e.errno, e.strerror)
line()

print "Elapsed time: %s s." % (time.time()-start)


----------------------------------------------------



#!/usr/bin/python
import os.path

def line():
    print "-" *50
 
def create_file():
    fname = "/tmp/test.file"
    check = os.path.exists(fname)
 
    if check == True:
        print "file is excist all ok"
    else:
        os.popen("touch /tmp/test.file")
        print "file has been created\n"

try:
    create_file()
    print "write to file\n"
    f=open("/tmp/test.file")
 
except IOError as e:
    print "I/O Error({0} : {1}) ".format(e.errno, e.strerror)
 




-------------------------------------------------------------------------


#!/usr/bin/python
import os

def create_file():
    fname = "/tmp/file.dat"
    check = os.path.exists(fname)
    if check == True:
        print "file is excist all ok"
    else:
        os.popen("touch /tmp/file.dat")
        print "file has been created\n"
try:
    create_file()
    with open("/tmp/file.dat","wt") as out_file:
        print "inserted"
        out_file.write("Marek Borkowski\n")
 
    with open("/tmp/file.dat", "rt") as in_file:
        text = in_file.read()
 
    print(text)
except:
    print "error"
 


Brak komentarzy:

Prześlij komentarz