您的位置:首页 > 其它

文件的读写操作

2014-09-20 19:06 190 查看
#!/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()

#这时候 你会看见原来的内容消失了(被覆盖了)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: