python关于文件操作

1 “”“文件的操作”""

1.1 #文件的打开用open,有返回值

f=open(“文件名”,“访问模式”) #返回值为变量f

f=open(“c.txt”,‘r+’)

  **1.2**                """文件的读取用read"""

print(f.read()) #如果read()这个函数没有指定参数,则返回文件中的所有内容

print(f.read(20))# 如果指定参数,从文件中读取数据的长度(单位是字节)

文件的关闭用close

f.close()

 **1.3**



            """readline单行读取,返回为字符串形式"""

f1=open(“c.txt”,‘r+’,encoding=‘utf-8’)

f1.write(“python is the best”)

print(type(f1.readline(7)))

f2=open(“c.txt”,‘r+’,encoding=‘utf-8’)

print(f2.readline())#readline用于读取一行数据,每执行一次读取一行,自动换行不重复

print(f2.readline())

print(f2.readline())

 **1.4**                """readlines多行读取,返回为集合"""

                   """a+,readlines是直接追加在内容后面的"""

f=open(“c.txt”,‘a+’)

print(f.readlines())

#\n用于前后换行,不至于粘在一起

f.write(“python biubi\n”)

f.write("\npython biubi")

f.close()

1.5 “”“w+,readlines是先把文件刷新再写入(覆盖)
执行结果返回文章所有的内容,并且以列表的形式返回”""

f=open(“c.txt”,‘w+’,encoding=‘utf-8’)

print(f.readlines())

f.write(“python is niu bi”)

f.close()

1.6例题:                  """复制改名"""

old=open(“liangliang.mp3”,‘rb’) #打开或新建文件

new=open(“凉凉.mp3”,‘wb’)

list=old.readlines() #读取旧文件并以列表返回

print(list)

for i in list: #遍历列表中所有内容并写入新文件

new.write(i)

print(new)

old.close() # 关闭文件

new.close()

猜你喜欢

转载自blog.csdn.net/qq_44090577/article/details/88356044