码迷,mamicode.com
首页 > 编程语言 > 详细

python--基础4 (文件操作)

时间:2019-06-15 15:15:56      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:路径   文件操作   lis   close   没有   readlines   enc   alt   你好   

python文件操作步骤

#第一步:调用文件
f=open(r'D:\untitled\venv\Include\blacklist.txt', 'r', encoding='gbk')
#第二部:使用文件
print(f.readlines())
#第三部:关闭文件
f.close()

#python中内置函数with可以自动关闭文件:
with open(r'D:\untitled\venv\Include\blacklist.txt', 'r', encoding='utf-8')as f:
    print(f.readlines())

三种调用文件的路径的写法

open(r'D:\untitled\venv\Include\blacklist.txt')  #r --read  只读,代表' '内的字符串没有其他含义不进行转义
open('D:\\untitled\\venv\\Include\\blacklist.txt')
open('D:/untitled/venv/Include/blacklist.txt')

读(rt)

read读取全部内容

with open(r'D:\untitled\venv\Include\blacklist.txt', 'r', encoding='gbk')as f:
    print(f.read())

...运行结果

艾妮
你好
hello
world

readline按行读取

with open(r'D:\untitled\venv\Include\blacklist.txt', 'r', encoding='gbk')as f:
    print(f.readline(2))

...运行结果

艾妮

readlines把内容以列表形式展现

with open(r'D:\untitled\venv\Include\blacklist.txt', 'r', encoding='gbk')as f:
    print(f.readlines())

...运行结果

['艾妮\n', '你好\n', 'hello\n', 'world\n']

覆盖写(wt)

with open(r'D:\untitled\venv\Include\blacklist.txt', 'w', encoding='utf-8')as f:
    f.write('你好不好')
with open(r'D:\untitled\venv\Include\blacklist.txt', 'r', encoding='utf-8')as f:
    print(f.readlines())

...运行结果

['你好不好']

追加写appand(at)

with open(r'D:\untitled\venv\Include\blacklist.txt', 'a', encoding='utf-8')as f:
    f.write('艾妮'+'\n')
with open(r'D:\untitled\venv\Include\blacklist.txt', 'r', encoding='utf-8')as f:
    print(f.read())

...运行结果

你好不好
艾妮
艾妮
艾妮

技术图片

python--基础4 (文件操作)

标签:路径   文件操作   lis   close   没有   readlines   enc   alt   你好   

原文地址:https://www.cnblogs.com/du-z/p/11027525.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!