Difference between revisions of "Python:Files"

From wiki
Jump to navigation Jump to search
m
Line 57: Line 57:
 
;sys.stdout.write(<string>)
 
;sys.stdout.write(<string>)
 
:Write to standard output
 
:Write to standard output
 +
 +
===Zip a file===
 +
Check [https://pymotw.com/2/zipfile/ this page].
 +
 +
<syntaxhighlight lang=python>
 +
import zipfile,zlib
 +
 +
zipname = filename+'.zip'
 +
zfile = zipfile.ZipFile(zipname, mode='w')
 +
if zfile:
 +
    zfile.write(filename, compress_type=zipfile.ZIP_DEFLATED)
 +
</syntaxhighlight>
  
 
==Read from standard input and keyboard==
 
==Read from standard input and keyboard==

Revision as of 11:01, 9 October 2018


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

Code example:

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

Code example:

import os
if os.path.isfile(filename):
    f1 =  open (filename,"r")
    for line in f1:
        <codeblock>
    f1.close()
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>
f1.write(line)
Write line to file opened on filehandle f1
sys.stdout.write(<string>)
Write to standard output

Zip a file

Check this page.

import zipfile,zlib

zipname = filename+'.zip'
zfile = zipfile.ZipFile(zipname, mode='w')
if zfile:
    zfile.write(filename, compress_type=zipfile.ZIP_DEFLATED)

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: ")