Learning notes on python file operation
# File operations:
Read:
F = open ("/ Users/zhouhaijun/python/01.py", "r")
X = f.read ()
Print x
Write:
F = open ("/ Users/zhouhaijun/python/file_01.py", "wb")
F.write ("ok")
F.close ()
Read:
F = open ("/ Users/zhouhaijun/python/file_01", "r")
Text = f.read () # text = f.read
Print text
Read one line:
Print f.readline () # read by line
The next function is to copy the file, reading and writing fifty characters at a time. The first parameter is the source document name, and the second parameter is the new file name
Def copyFile (oldfile, newfile):
F1 = open (oldfile, "r")
F2 = open (newfile, "w")
While 1:
Text = f1.read (50)
If text = "":
Break
F2.write (text)
F1.close ()
F2.close ()
Return
The next example is a line processor, where the function filterFile copies a file and sets the old
Lines in the file that do not begin with "#" are written to the new file:
Def fileterFile (old, new):
Sfile = open (old, "r")
Dfile = open (new, "w")
While 1:
Text = sfile.readline ()
If text = "":
Break
Elif:
Text [0] = "#":
Continue
Else:
Dfile.write (text)
Sfile.close ()
Dfile.close ()