Difference between revisions of "Python:Files"

From wiki
Jump to navigation Jump to search
Line 81: Line 81:
 
def main():
 
def main():
  
     logfile = openlog()
+
     logfile,logfilename = openlog()
     logfile2 = openlog(<apath>)
+
     logfile2,dummy = openlog(<apath>)
 
     writelog(logfile,"This is in the logfile with generated name")
 
     writelog(logfile,"This is in the logfile with generated name")
 
     writelog(logfile2,"This is in the logfile with specified name")
 
     writelog(logfile2,"This is in the logfile with specified name")
Line 109: Line 109:
 
     except UnboundLocalError:
 
     except UnboundLocalError:
 
         logfile = open (logfilename,"a")
 
         logfile = open (logfilename,"a")
     return(logfile)
+
     return(logfile,logfilename)
  
 
main()
 
main()
 
</syntaxhighlight>
 
</syntaxhighlight>

Revision as of 11:14, 12 September 2018


glob.glob(filespec)
Return a list of files matching 'filespec'.

Code example:

import glob
files = glob.glob(filespec)
open (filename,"r")
open filename for read and return the filehandle. Use w for write.

Code example:

import os
if os.path.isfile(filename):
    f1 =  open (filename,"r")
with open (filename,"r") as file
Open filename for read and close at the end of the loop

Code example:

with open (filename,"r") as file:
    for line in file:
        <codeblock>
f1.read(size)
Return 'size' bytes from the file as string. If size is omitted or 0 the entire file is returned.
f1.readlines()
list(f1)
Return all lines from file as list.
fileinput.input()
Read through all files specified on the commandline.
If there are no files on the commandline read standard input
import fileinput

for line in fileinput.input():
    <codeblock>

Read from standard input and keyboard

Read from standard input

import sys

for line in sys.stdin:
    <codeblock>

Prompt and read from keyboard into a

a = input("Prompt: ")

In python2

a = raw_input("Prompt: ")

Open and write logfiles

def usage():
    print ("Usage: "+__file__)
    print("Open and write to logfiles")
    sys.exit(1)


import re
from datetime import datetime

def main():

    logfile,logfilename = openlog()
    logfile2,dummy = openlog(<apath>)
    writelog(logfile,"This is in the logfile with generated name")
    writelog(logfile2,"This is in the logfile with specified name")

    return


def writelog (logfile,message):
    try:
        logfile.name
    except AttributeError:
        print("ERROR: Logfile is not open")
        usage()
    else:
        message = datetime.now().strftime("%y%m%d_%H%M")+" "+message+"\n"
        logfile.write(message)
    return()


def openlog (logfilename = ''):
    if logfilename == '':
        logfilename = re.sub('/bin/','/log/',__file__)
        logfilename += '_'+datetime.now().strftime("%y%m%d_%H%M")+'.log'
    try:
        logfile.name
    except UnboundLocalError:
        logfile = open (logfilename,"a")
    return(logfile,logfilename)

main()