---
title: "Python 文件操作"
author: "cai555"
date: "2009-04-09T16:51:08Z"
tags: ["D语言", "F#", "OS", "Python", "Web"]
slug: "python"
draft: false
lastmod: "2009-04-09T16:51:08Z"
id: 364482
url: "https://cai555.iteye.com/blog/364482"
---

# [Python 文件操作](http://www.cnblogs.com/yoshow/archive/2007/12/04/982284.html)

文件操作是一个语言和外界联系的主要方法.

现在以txt为例简单的讲一下.

首先是建立关联...假设在存在以下文件 e:test.txt

This is line #1  
This is line #2  
This is line #3  
END

&gt;&gt;&gt; f = file('e:\\test.txt', 'r')

关键字的第一部分，是文件路径及名称。注意这里面，路径需要用\\

第二部分，是对文件的模式或者叫权限，一般有以下3种 "r" (read)， "w" (write)和 "a"(append).

之后，就可以利用  
f\_content = infile.read()  
f\_content = infile.readlines()  
来读取文件内容了

&gt;&gt;&gt; f = file('e:\\test.txt', 'r')  
&gt;&gt;&gt; f\_content = f.read()  
&gt;&gt;&gt; print f\_content  
This is line #1  
This is line #2  
This is line #3  
END  
&gt;&gt;&gt; f.close()  
&gt;&gt;&gt;  
&gt;&gt;&gt; infile = file('e:\\test.txt', 'r')  
&gt;&gt;&gt; f = file('e:\\test.txt', 'r')  
&gt;&gt;&gt; for f\_line in f.readlines():  
print 'Line:', f\_line

Line: This is line #1  
Line: This is line #2  
Line: This is line #3  
Line: END

&gt;&gt;&gt; f.close()  
&gt;&gt;&gt;

然后是文件的写入

1\. &gt;&gt;&gt; f=file('e:\\test.txt','w')  
2\. &gt;&gt;&gt; f.write('billrice')  
3\. &gt;&gt;&gt; f.write('testtest')  
4\. &gt;&gt;&gt; f.write('entern')  
5\. &gt;&gt;&gt; f.writelines(\['billrice','ricerice'])  
6\. &gt;&gt;&gt; f.close()  
7\. &gt;&gt;&gt;  
8\. &gt;&gt;&gt; f=file('e:\\test.txt','r')  
9\. &gt;&gt;&gt; content=f.read()  
10\. &gt;&gt;&gt; print content  
11\. billricetesttestenter  
12\. billricericerice  
13\. &gt;&gt;&gt;

需要注意的是...在f.close()之前，c盘下面只有一个空空的test.txt，f.close()的作用相当于最后的存盘。

删除文件：

name='e:1.txt'  
os.remove(name)

压缩文件：

import os  
import zipfile  
import time  
\# 压缩目录  
source\_dir= r'F:web'  
\# 按时间生成文件名称  
target\_file = time.strftime('%Y%m%d%H%M%S') + '.zip'

myZipFile = zipfile.ZipFile(target\_file, 'w' )# 压缩所有文件，包含子目录  
for root,dirs,files in os.walk(source\_dir):  
for vfileName in files:  
fileName = os.path.join(root,vfileName)  
myZipFile.write( fileName, fileName, zipfile.ZIP\_DEFLATED )  
\# 压缩完成  
myZipFile.close()