Home > Backend Development > Python Tutorial > Sample code for reading and writing files and storage in Python programming

Sample code for reading and writing files and storage in Python programming

高洛峰
Release: 2017-03-13 18:00:11
Original
1444 people have browsed it

This article mainly introduces examples of reading and writing files and storage in PythonProgramming, including examples of using cPickle storage to store objects. Friends in need can refer to the following

1. Writing and reading files


#!/usr/bin/python 
# -*- coding: utf-8 -*- 
# Filename: using_file.py 
# 文件是创建和读取 
 
s = '''''我们都是木头人, 
不许说话不许动!''' 
 
# 创建一个文件,并且写入字符 
f = file('test_file.txt', 'w') 
f.write(s) 
f.close() 
 
# 读取文件,逐行打印 
f = file('test_file.txt') 
while True: 
  line = f.readline() 
  # 如果line长度为0,说明文件已经读完了 
  if len(line) == 0: 
    break 
  # 默认的换行符也读出来了,所以用逗号取代print函数的换行符 
  print line, 
f.close()
Copy after login

Execution results:


我们都是木头人,
不许说话不许动!
Copy after login


2. Memory writing and reading


#!/usr/bin/python 
# -*- coding: utf-8 -*- 
# Filename using_pickle.py 
# 使用存储器 
 
#加载存储器模块,as后面是别名 
#import pickle as p 
#书上说cPickle比pickle快很多 
import cPickle as p 
 
listpickle = [1, 2, 2, 3] 
picklefile = 'picklefile.data' 
 
f = file(picklefile, 'w') 
# 写如数据 
p.dump(listpickle, f) 
f.close() 
 
del listpickle 
 
f = file(picklefile) 
# 读取数据 
storedlist = p.load(f) 
print storedlist 
f.close()
Copy after login


Execution results:


[1, 2, 2, 3]
Copy after login

Let’s look at an example of using cPickle storage to store objects


#!/usr/bin/python 
#Filename:pickling.py 
 
import cPickle as p 
 
shoplistfile = 'shoplist.data' 
 
shoplist = ['apple', 'mango', 'carrot'] 
 
f = file(shoplistfile, 'w') 
p.dump(shoplist, f) 
f.close() 
 
del shoplist 
 
f = file(shoplistfile) 
storedlist = p.load(f) 
print storedlist
Copy after login

The above is the detailed content of Sample code for reading and writing files and storage in Python programming. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template