#文件操作:
读:
f = open(“/Users/zhouhaijun/python/01.py”,”r”)
x = f.read()
print x
写:
f = open(“/Users/zhouhaijun/python/file_01.py”,”wb”)
f.write(“ok”)
f.close()
读:
f = open(“/Users/zhouhaijun/python/file_01″,”r”)
text = f.read() #text = f.read(100)
print text
读取一行:
print f.readline() #按行读取
接下来的函数是拷贝文件,一次读写五十个字符。第一个参数是源文
件名,第二个参数是新文件名
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
接下来的例子是行处理程序,函数filterFile拷贝一个文件,同时将旧
文件中不是以“#”开头的行写入新文件中:
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()
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/193325.html