---restore content starts---
Read file:
Fin=open ("Test.txt")
Read=fin.readline ()-----read a line
For line in Fin:
Print (line)
Fin.close ()
Read=fin.read ()----Read all content
Write file:
Fout=open (' Test.txt ', ' W ')----Erase the original contents of the file and write
Line1= ' Good afternoon '
Fout.write (line1)---Write argument must be a string
Fout.close ()
Fout=open (' Test.txt ', ' a ')----append content to the source file
Format operator---%: Converts an expression to a string
Line= ' in%d years I had spotted%g%s '% (3,0.1, ' camels ')
File name and path:
Import OS----OS W provides functions for manipulating files and directories
CWD=OS.GETCWD ()----Get the current directory
Path=os.path.abspath (' test.txt ')----get the absolute path to the file
Os.path.exists (' test.txt ')----checks if a file or directory exists, returns a Boolean type
Os.path.isdir (' test.txt ')----Check if it is a directory
Os.listdir (CWD)---Returns a list of files in the specified directory
Os.path.isfile (' Test ')---Check if it is a file
Os.path.join (dirname,name)----accept a directory and file name and spell it as a full path
Catching Exceptions:
Try
Fin=open (' Test.txt ')
For line in Fin:
Print (line)
Fin.close ()
Except
Print (' Something is wrong ')
To write a module:
If you have a file: example.py
Importing this file: import example
Using Functions in example.py: Example.linecount ()
Os.path.
File---Python