`

Python 文件操作

阅读更多

Python 文件操作

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

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

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

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

>>> f = file('e:\test.txt', 'r')

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

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

之后,就可以利用
f_content = infile.read()
f_content = infile.readlines()
来读取文件内容了

>>> f = file('e:\test.txt', 'r')
>>> f_content = f.read()
>>> print f_content
This is line #1
This is line #2
This is line #3
END
>>> f.close()
>>>
>>> infile = file('e:\test.txt', 'r')
>>> f = file('e:\test.txt', 'r')
>>> 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

>>> f.close()
>>>


然后是文件的写入

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


需要注意的是...在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()

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics