Use of glob module in Python code
Program to read and display files in a directory with a particular extension using glob module are discussed in this section
Program list_files.py
#!/usr/bin/python
import glob
import string
import os
import commands
files = glob.glob("*.htm*")
for filename in files:
print "file in directory %s" % (filename)
Result :
Suppose we want to read a directory for the html files (*.htm) and print the names of the files.
For the following files vhdl1.htm, vhdl2.htm, …, vhdln.htm in a directory
From the python shell we run
>> list_files.py
file in directory vhdl1.htm
file in directory vhdl2.htm
...
file in directory vhdln.htm
Following list of programs
are discussed in this sec:
¶ File Operations:
- Open and read file from within the python program as a single string. Command line arguments lists as string with ‘sys.argv’.
- Use of glob module in Python code . Read file using classes, global variables and functions. Program to open and write file.
- Specify files to be written from the command line. File writes using classes and global variables
¶ Program to read file, filter text, conversion to HEX, conversion from Hexadecimal to Signed Magnitude.S Steps for conditional statements, converting string to hexadecimalvalue, strip of white space at end, converting 12 bit hexadecimal values to 12 bit signed values.
¶ Advanced python code to cover UNIX shell commands, read lines from a text file, ‘sysargv’ command line operations, use of class and multiple functions.
¶ Write a program to generate diamond pattern.
¶ Implement Python function calls to different classes.
¶ Python read binary files, use of struct.unpack.
¶ Python error’s with complete code examples:-
- TypeError: __init__() takes exactly 2 arguments (1 given),
- TypeError: 'str' object is not callable, TypeError: not all arguments converted during string formatting,
- AttributeError: ** instance has no attribute **
Hope you liked! this page. Don't forgot to access relevant previous and next sections
with links below.