文件的读写操作

#!/usr/bin/python
#-*- coding:utf8 -*-

#这一章主要介绍文件以及操作
import os

#创建文件 并写入数据

write_context = """
    This is a test from jack
"""

f = file("jack.txt", "w")
f.write(write_context)
f.close()

#ok 执行程序后 可以看见当前文件夹下有jack.txt了

#文件的读取
#首先建立一个文件 test.txt 内容如下
"""Two years ago, I fall in love with you,
From that day, I miss you every day and
Leave you in my mind, heart and sour,
Today I show my love to you,otherwise,
I was rejected by you.He he, 程序员的爱情!
"""



#现在第一种方式读取
f1 = open("test.txt")
while 1:
    line = f1.readline()
    if len(line):
        print line, #防止换行 加以个逗号
    else:
        break
f1.close()
print

#进行整体一起读
f2 = open("test.txt")
lines = f2.readlines()
for line in lines:
    print line,
f2.close()
print


f3 = open("test.txt")
context = f3.read()
print context
f3.close()
print

#read函数还可以设置字节数的读 一次读取10个等
f4 = open("test.txt")
read1 = f4.read(5)
print read1
read2 = f4.read(10)  #可以文件指针一直在移动
print read2
read3 = f4.read(20)
print read3

f4.close()
print



#写文件
#可以有不同的方式 写 例如追加写

f5 = file("jack.txt","a+")
data = "ni hao, Hello \n One world, One dream\n"
f5.write(data)
f5.close()

#还有一个writelines函数
f6 = open("jack.txt","w+")
list_data = ["Jack\n", "I love you!\n", "你在意淫吗?"]
f6.writelines(list_data)
f6.close()

#这时候 你会看见原来的内容消失了(被覆盖了)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值