Difference between revisions of "Python:Files"

From wiki
Jump to navigation Jump to search
(Created page with "Category:Python ;glob.glob(filespec) :Return a list of files matching 'filespec'. Code example: <syntaxhighlight lang=python> import glob files = glob.glob(filespec) </sy...")
 
Line 27: Line 27:
 
     for line in file:
 
     for line in file:
 
         <codeblock>
 
         <codeblock>
 +
</syntaxhighlight>
 +
 +
;f1.read(size)
 +
:Return 'size' bytest from the file as string if size is omited the entire file is returned.
 +
 +
;f1.readlines(size)
 +
;list(f1)
 +
:Return ('size') lines from file as list.
 +
 +
Read through all files specified on the commandline.
 +
If there are no files on the commandline read standard input
 +
<syntaxhighlight lang=python>
 +
import fileinput
 +
 +
for line in fileinput.input():
 +
    <codeblock>
 +
</syntaxhighlight>
 +
 +
==Read from standard input==
 +
 +
 +
Read from standard input
 +
<syntaxhighlight lang=python>
 +
import sys
 +
 +
for line in sys.stdin:
 +
    <codeblock>
 
</syntaxhighlight>
 
</syntaxhighlight>

Revision as of 21:32, 17 January 2018


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

Code example:

import glob
files = glob.glob(filespec)
open (filename,"r")
open filname 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' bytest from the file as string if size is omited the entire file is returned.
f1.readlines(size)
list(f1)
Return ('size') lines from file as list.

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

Read from standard input

import sys

for line in sys.stdin:
    <codeblock>