文件的读写操作
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()
#这时候 你会看见原来的内容消失了(被覆盖了)
#-*- 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()
#进行整体一起读
f2 = open("test.txt")
lines = f2.readlines()
for line in lines:
print line,
f2.close()
f3 = open("test.txt")
context = f3.read()
print context
f3.close()
#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()
#写文件
#可以有不同的方式 写 例如追加写
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()
#这时候 你会看见原来的内容消失了(被覆盖了)
相关文章推荐
- lr中读写文件操作代码(原创)
- VB 写的二进制文件读写数据库操作模块
- 对于大文件的读写操作
- 含读写及替换字符的复制文件操作
- 对WEB.Config文件进行(读写操作)
- JDom操作XML文件读写
- 一个非常非常非常基础的程序,写的不好,但是一般的文件读写操作及字符处理函数都涉及到了..新手学习用的
- 第二十三课:PHP中文件读写操作
- 另一个文件读写操作
- VC++中,配置文件的读写操作
- Document/View的交互 -- 文件读写操作
- Document/View的交互 -- 文件读写操作
- 市面上所有号称"虚拟机","防火墙"的实时监控杀毒软件无一不是使用的IFSHOOK技术.但是同时也有一些朋友不断写MAIL给我打听如何实现读写的监控.下面给出用VTOOLSD写的代码.也就是所有实时杀毒软件的奥秘.同时,很多拦截文件操作的软件,例如对目录加
- Java 中对文件的读写操作之比较
- C++中对文件进行读写操作
- JAVA100例]034、读写文件(字符操作)(java100例)
- [C++]文件读写操作
- 文件读写操作
- 文件读写操作
- Java 中对文件的读写操作之比较