您的位置:首页 > 编程语言 > Python开发

python 中的 read readline readlines 与 wirte writelines

2013-10-22 16:28 513 查看
先PS下背景吧,签了前途未卜的大华为核心网,这两天闲来无事,终于有时间学学自己唠叨了研究僧两年的python了,选的是网上croosin先生的讲义

地址:http://www.crossin.me/forum.php

# python

#   讨论下
#   read readline readlines
#   wirte writeline writelines
#   以data.txt为例吧





f = file('data.txt') 
data = f.read()
print data
f.close()


f = file('data.txt')
data = f.readline()
print data
f.close()

f = file('data.txt')
data = f.readlines()
print data
f.close()



结果:



# read读取文档的所有内容
# readline读取文档的一行内容,然后自动跳到下一行(验证如下)
# readlines逐行讲文档中的内容读进一个list


f = file('data.txt')
data = []
for i in range(3):
    data1 = f.readline()
    data.append(data1)
print data
f.close()


结果:



下面讲write writelines(没有writeline 哦!)

f = file('D:\Python 工程\data.txt') 
data = f.read()
print data
f.close()

fo = file('data_copy.txt','a')
fo.write(data)
fo.close()


结果:



然后运行

# 为了不建立这么多烂七八糟的文件,我们选用append模式
f = file('D:\Python 工程\data.txt') 
data = f.read()
print data
f.close()
fo = file('data_copy.txt','a')
fo.writelines(data)
fo.close()

结果:



可见write 跟 writeline的结果是一样的

那么两者的区别是什么呢,百度‘write writelines python’第一条的结果是:

Use the write() function to write a fixed sequence of characters -- called a string -- to a file. You cannot use write() to write arrays or Python lists to a file. If you try to use write() to save a list of strings, the Python
interpreter will give the error, "argument 1 must be string or read-only character buffer, not list."

write函数可以用来对文件写入一个字符串,但不能使用write 对文件写入一个数组或者list,如果你企图使用write对文件写入一个字符串list表单,Python将报错

即如果运行

f = file('D:\Python 工程\data.txt') 
data = f.readlines() #data成为一个list
print data
f.close()
fo = file('data_copy.txt','a')
fo.write(data)
fo.close()

fo.write(data)

在fo.write(data)处会报错

TypeError: expected a character buffer object(应该是一个字符串)

继续看百度给的知识:

The writelines() function also writes a string to a file. Unlike write(), however, writelines can write a list of strings
without error. For instance, the command nameOfFile.writelines(["allen","hello world"]) writes two strings "allen" and "hello world" to the file foo.txt. Writelines() does not separate the strings, so the output will be "allenhello world."writelines同样是对文件写入一个字符串,但是跟write不通的是,writelines可以操作list字符串。比如,
输入命令 offile.writelines(["allen","hello world"]) 将两个字符串"allen" and "hello world" 同时写入了文件foo.txt中。但writelines 并没有分开这些字符串,输出应该是"allenhello world."

例:逐句运行

>>> results = ['HI!','MY name is Lilei']
>>> fo = file('data_copy.txt','a')
>>> fo.writelines(results)

>>> fo.close()
>>> fo = open('data_copy.txt')
>>> data = fo.read()
>>> print data

你会得到结果为

HI!MY name is Lilei

这样可能看起来不方便,假如我们想要换行怎么办??

其实只要认为的假如回车符即可

results = ['HI!\n','MY name is Lilei\n']
fo = file('data_copy.txt','a')
fo.writelines(results)
fo.close()
fo = open('data_copy.txt')
data = fo.read()
print data




Python 菜鸟,有问题请留言指教
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python