python文件的基本操作


1 #创建文件
context='''hello world,
hello china
'''
f=file("hello.txt",'w') #打开文件,若没有就创建吧
f.write(context) #把字符串写入文件
f.close() #关闭文件.释放资源



#############################################################################################
2 #文件的写入操作。
#使用readline()读文件
f=open("hello.txt")
while True:
line=f.readline()
if line:
print line,
else:
break
f.close()

#使用readlines()读文件
f=file("hello.txt")
lines=f.readlines() #返回一个列表
for line in lines:
print line
f.close()

#使用read()读文件
f=open("hello.txt")
context=f.read()
print context
f.close()
'''
输出结果为:
hello world,
hello china
'''


f=open("hello.txt")
context=f.read(5) #第一次读取五个字符。
print context
print f.tell()
context=f.read(5) #再次读取五个字符
print context
print f.tell()
'''
输出结果为:
hello
5
worl
10
'''


###########################################################################
#文件的写入操作
#使用writelines()读文件
f=file("hello.txt","w")
li = ["hello world ","hello china "]
f.writelines(li)
f.close()

#追加新的内容到文件
f=file("hello.txt","a+")
new_context="goodbye"
f.write(new_context)
f.close()



###################################################################################
#文件的删除
import os
file("hello.txt","w")
if os.path.exists("hello.txt"):
os.remove("hello.txt")








#################################################################
#文件的复制操作
#使用read()、write()实现拷贝
#创建文件hello.txt
src=file("hello.txt","w")
li =["hello world ","hello china "]
src.writelines(li)
src.close()

#把hello.txt拷贝到hello2.txt
src=file("hello.txt","r")
dst=file("hello2.txt","w")
dst.write(src.read())
src.close()
dst.close()

#shutil模块实现文件的拷贝
import shutil
shutil.copyfile("hello.txt","hello2.txt")
shutil.move("hello.txt","../") #将hello.txt移动到上一级目录
shutil.move("hello2.txt","hello3.txt") #将hello2.txt剪切到hello3.txt



################################################################################################
#修改文件名
import os
li =os.listdir(".")#listdir()表示读取目录,其中点表示读取当前目录。
print li
if "hello3.txt" in li:
os.rename("hello3.txt","hi.txt")
elif "hi.txt" in li:
os.rename("hi.txt","hello3.txt")






##########################################################################################################
#修改后缀名
import os
files = os.listdir(".")
for filename in files:
pos =filename.find(".") #用find()方法来进行查找点
if filename[pos+1:]=="html": #计算到点后面一个字符的位置,
newname=filename[:pos+1]+"htm" #将后缀名改为htm
os.rename(filename,newname)

#import os
files =os.listdir(".")
for filename in files:
li = os.path.splitext(filename) #对文件名进行切分,把点前面的文件名与后缀名进行切分,然后存储到li列表里面。
if li[1]=="html":
newname=li[0]+".htm"
os.rename(filename,newname)
原文地址:https://www.cnblogs.com/papapython/p/7494570.html