python//Jan.18th,2020//文件

Jan.17th,2020
##文件

#读取文件
#文件要保存在程序所在的目录中
#with open('s.txt') as s:    #open()函数,接受一个参数,要打开的文件的名称 对应的有close()函数
#    contents=s.read()       #关键字with 不需要访问文件将其关闭
#    print(contents)
#    print(contents.rstrip()) 删除末尾的空行

#文件路径
#Linux/OS X  斜杠/
#windows    反斜杠\
#with open('venv\s.txt') as s:
#    contents=s.read()
#    print(contents)

##绝对路径
#with open(r'C:\360CloudEnterprise\s.txt') as s: #单引号前加r
#    contents=s.read()
#    print(contents)

#逐行读取
#with open(r'C:\360CloudEnterprise\s.txt') as s: #单引号前加r
#    for s in s:
#        #print(s)
#        print(s.rstrip())

#创建一个包含文件各行内容的列表
#with open(r'C:\360CloudEnterprise\s.txt') as ss:
#    s=ss.readlines()
#for s in s:
#    print(s.rstrip())

#使用文件内容
#filename=r'C:\360CloudEnterprise\s.txt'
#with open(filename) as file_object:
#    lines=file_object.readlines()
#cxk=''
#for line in lines:
#    cxk+=line.rstrip()  #区分rstrip() strip()
#print(cxk)
#print(len(cxk))

#写入空文件
#with open(r'C:\Users\Administrator\Desktop\idocdown3210\Fish-v3210-1212\kpdf\圆周率小数点后100万位.txt','w') as file_object:
#    file_object.write("i love you")
#    #实参'w'告诉Python,要已写入模式打开这个文件,同样,读取模式('r'),附加模式 ('a')
#    #能够读取和写入('r+')

#写入多行
#with open(r'C:\Users\Administrator\Desktop\idocdown3210\Fish-v3210-1212\kpdf\圆周率小数点后100万位.txt','w') as file_object:
#    file_object.write("I love you.\n")
#    file_object.write("I love programing.\n")
#    file_object.write("I love playing game.\n")

#附加到文件 (原来的内容在,添加其他内容)
#with open(r'C:\Users\Administrator\Desktop\idocdown3210\Fish-v3210-1212\kpdf\圆周率小数点后100万位.txt','a') as file_object:
#    file_object.write("I love you.\n")
#    file_object.write("I love programing.\n")
#    file_object.write("I love playing game.\n")


发布了38 篇原创文章 · 获赞 2 · 访问量 1167

猜你喜欢

转载自blog.csdn.net/weixin_44811068/article/details/104027138