python文件操作

一、常规的文件操作

1.文件的一般操作:打开文件、读取文件、关闭文件(经常忘记)

a.读取文件:open(path,encoding,errors)

#

path-路径

encoding-打开方式:r(读)/rb(二进制读)/r+/w+/w(不存在就创建)/w+(读写)

errors-错误处理:一般情况,errors='ignore'

b.读取文件的集中操作

.读取全部内容

f=open('D:/nihap.txt','r+',encoding='ignore') /f=open("D:\\nihao.txt",'r+',encoding='ignore')

str1=f.read()

.从全部内容中读取部分

str2=f.read(10)

.按行读取,并以表格的形式输出

str3=f.readlines() #readline()-读取一行,readline(10)-一行读取是个字符,readlines(10)-每行读取十个字节

print(str3)

c.关闭文件

.f.close()

2.完整格式

try:

  f=open(path,'r',errors='ignore')

  str=f.readlines(10)

  print(str)

  

except:

  print("文件读取出错")

finally:#不管怎样都会执行finally\

  f.close()

二、with-自动关闭文件

try:

  with open(path) as f:

    content=f.read()

    print(content)

except:

  print("读取失败")

三、注意事项

win的文件路径在程序中无法识别?

‘\’-表示在程序中转译,需要用'\\'再次转译路径 或者/‘进行分割

posted on 2018-10-19 21:03  RiceAChen  阅读(72)  评论(0)    收藏  举报

导航