python3的文件操作1

先来看下面的带码:

# 创建文件
context = '''hello world'''

f = open('hello.txt', 'w')          # 打开文件
f.write(context)                # 把字符串写入文件
f.close()                       # 关闭文件

第3行调用open()创建文件hello.txt,第4行写入,第5行调用close(),释放对象f占用的资源。
在同级目录下会生成hello.txt文档。

接下来是文件读取:

# 使用readline()读文件
f = open("hello.txt")
while True:
    line = f.readline()
    if line: 
        print (line)
    else:
        break
f.close()

此程序读取文件里的每一行。
输出为:
hello world

多行读取则是使用readlines()

# 使用readlines()读文件
f = open('hello.txt')
lines = f.readlines()
for line in lines:              # 一次读取多行内容
    print (line)
f.close()       

一次性读取read():

# 使用read()读文件
f = open("hello.txt")
context = f.read() 
print (context)
f.close()

控制read()参数:

f = open("hello.txt")
context = f.read(5)           # 读取文件前5个字节内容
print (context)
print (f.tell())                # 返回文件对象当前指针位置
context = f.read(5)          # 继续读取5个字节内容
print (context)
print (f.tell())               # 输出文件当前指针位置
f.close()

接下来看看文件的写入:

# 使用writelines()写文件
f = open("mygirl.txt", "w+")
li = ["hello world\n", "hello China\n"]
f.writelines(li)
f.close()  

追加新内容的话,使用a+模式:

# 追加新的内容到文件
f = file("mygirl.txt", "a+")         # 写入方式为追加a+
new_context = "goodbye"
f.write(new_context)
f.close()

如果需要写入文件的字符串非常多,可以使用writelines()加快写文件的速度。

再简单看下文件的删除:

import os

file("hello.txt", "w")
if os.path.exists("hello.txt"):
    os.remove("hello.txt")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值