Python文件读写
2014-08-12 14:56
190 查看
文件处理
f= file('poem.txt', 'w')
# open for 'w'riting模式可以为读模式('r')、写模式('w')或追加模式('a')
f.write(poem) # write text to file
f.close()
f = file('poem.txt')
# if no mode is specified, 'r'ead mode is assumed by default
while True:
line = f.readline()
if len(line) == 0: # Zero length indicates EOF
break
print line,
# Notice comma to avoid automatic newline added by Python
f.close() # close the file
注意,因为从文件读到的内容已经以换行符结尾,所以我们在print语句上使用逗号来消除自动换行
储存器
Python提供一个标准的模块,称为pickle。使用它你可以在一个文件中储存任何Python对象,之后你又可以把它完整无缺地取出来。这被称为 持久地 储存对象。
还有另一个模块称为cPickle,它的功能和pickle模块完全相同,只不过它是用C语言编写的,因此要快得多(比pickle快1000倍)。你可以使用它们中的任一个,而我们在这里将使用cPickle模块。记住,我们把这两个模块都简称为pickle模块。
import cPickle as p
shoplistfile = 'shoplist.data'
# the name of the file where we will store the object
shoplist = ['apple', 'mango', 'carrot']
# Write to the file
f = file(shoplistfile, 'w')
p.dump(shoplist, f) # dump the object to a file把对象储存到打开的文件中
f.close()
del shoplist # remove the shoplist
# Read back from the storage
f = file(shoplistfile)
storedlist = p.load(f)
print storedlist
f= file('poem.txt', 'w')
# open for 'w'riting模式可以为读模式('r')、写模式('w')或追加模式('a')
f.write(poem) # write text to file
f.close()
f = file('poem.txt')
# if no mode is specified, 'r'ead mode is assumed by default
while True:
line = f.readline()
if len(line) == 0: # Zero length indicates EOF
break
print line,
# Notice comma to avoid automatic newline added by Python
f.close() # close the file
注意,因为从文件读到的内容已经以换行符结尾,所以我们在print语句上使用逗号来消除自动换行
储存器
Python提供一个标准的模块,称为pickle。使用它你可以在一个文件中储存任何Python对象,之后你又可以把它完整无缺地取出来。这被称为 持久地 储存对象。
还有另一个模块称为cPickle,它的功能和pickle模块完全相同,只不过它是用C语言编写的,因此要快得多(比pickle快1000倍)。你可以使用它们中的任一个,而我们在这里将使用cPickle模块。记住,我们把这两个模块都简称为pickle模块。
import cPickle as p
shoplistfile = 'shoplist.data'
# the name of the file where we will store the object
shoplist = ['apple', 'mango', 'carrot']
# Write to the file
f = file(shoplistfile, 'w')
p.dump(shoplist, f) # dump the object to a file把对象储存到打开的文件中
f.close()
del shoplist # remove the shoplist
# Read back from the storage
f = file(shoplistfile)
storedlist = p.load(f)
print storedlist
相关文章推荐
- 测试成功的Python中文文件读写脚本
- python Ini文件读写
- Python文件的读写
- python对文件进行读写操作
- python文件读写
- Python读写Unicode文件
- Python对unicode文件的读写和使用正则表达式
- python读写UCS-2 big/little endian(utf-16-be/utf-16-le)格式的文件
- [Python]读写文件方法
- python基础5--文件操作--字符串读写
- Python字符集编码和文件读写
- Python读写文件
- Python读写文件
- Python学习笔记--文件读写
- Python读写文件
- Python open读写文件实现脚本
- Python open读写文件实现脚本
- Python天天美味(17) - open读写文件
- 使用Python进行二进制文件读写
- python基础6--文件操作--对象的读写