Home Backend Development Python Tutorial Examples of reading, writing, compressing and decompressing files using Python

Examples of reading, writing, compressing and decompressing files using Python

Apr 01, 2017 pm 03:45 PM

读写文件
首先看一个例子:

f = open('thefile.txt','w')  #以写方式打开,
try:
  f.write('wokao')finally:
  f.close()
Copy after login

文件的打开方式:

f = open(‘文件','mode')
‘r':只读(缺省。如果文件不存在,则抛出错误)
‘w':只写(如果文件不存在,则自动创建文件),此时无法调用f.read()方法,且当调用f.write()时,将清空文件原有内容
‘a':附加到文件末尾
‘r+':读写
Copy after login

如果需要以二进制方式打开文件,需要在mode后面加上字符”b”,比如”rb”,”wb”等

文件的属性

f.closed #标记文件是否已经关闭,由close()改写
f.encoding #文件编码
f.mode #打开模式
f.name #文件名
f.newlines #文件中用到的换行模式,是一个tuple
f.softspace #boolean型,一般为0,据说用于print
Copy after login

文件的读写方法:

f.read([size]) #size为读取的长度,以byte为单位
f.readline([size]) #读一行,如果定义了size,有可能返回的只是一行的一部分
f.readlines([size]) #把文件每一行作为一个list的一个成员,并返回这个list。
其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长,
也就是说可能只读到文件的一部分
f.write(str) #把str写到文件中,write()并不会在str后加上一个换行符
f.writelines(seq) #把seq的内容全部写到文件中。这个函数也只是忠实地写入,不会在每行后面加上任何东西
f.close() #关闭文件
f.flush() #把缓冲区的内容写入硬盘
f.fileno() #返回一个长整型的”文件标签“
f.isatty() #文件是否是一个终端设备文件(unix系统中的)
f.tell() #返回文件操作标记的当前位置,以文件的开头为原点
f.next() #返回下一行,并将文件操作标记位移到下一行。把一个file用于for … in file这样的语句时,
就是调用next()函数来实现遍历的
f.seek(offset[,from]) #将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的,
一般为正数。但如果提供了from参数就不一定了,from可以为0表示从头开始计算,1表示以当前位置为原点计算。
2表示以文件末尾为原点进行计算。需要注意,如果文件以a或a+的模式打开,每次进行写操作时,
文件操作标记会自动返回到文件末尾。
f.truncate([size]) #把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。
Copy after login

Python在读取一个文件时,会记住其在文件中的位置,如果第二次仍需要从头读取,则需要调用f.seek(0)重新从头开始读取。

一些例子:

>>> f = open('hi.txt','w')
>>> f.closed
False
>>> f.mode
'w'
>>> f.name
'hi.txt'
>>> f.encoding
Copy after login

压缩和解压缩文件(zip/unzip)
1,单个文件压缩成zip文件

#!/usr/bin/python
import zipfile
f = zipfile.ZipFile('archive.zip','w',zipfile.ZIP_DEFLATED)
f.write('1.py')
f.write('/root/install.log')
f.close()
Copy after login

仔细观察压缩以后的archive.zip,里面有一个1.py和一个root的目录,root目录下有一个install.log
ZIP_DEFLATED是压缩标志,如果使用它需要编译了zlib模块,如果仅仅是打包而不压缩的话,可以改为zipfile.ZIP_STORED

2,把zip文件解压缩

#!/usr/bin/python
import zipfile
zfile = zipfile.ZipFile('archive.zip','r')
for filename in zfile.namelist():
  data = zfile.read(filename)
  file = open(filename, 'w+b')
  file.write(data)
  file.close()
Copy after login

如果archive.zip里有目录,则在当前目录下也应该存在对应的目录,否则会报错。

3,把整个文件夹压缩

#!/usr/bin/python
import zipfile
import os
f = zipfile.ZipFile('archive.zip','w',zipfile.ZIP_DEFLATED)
startdir = "c:\\\\mydirectory"
for dirpath, dirnames, filenames in os.walk(startdir):
  for filename in filenames:
    f.write(os.path.join(dirpath,filename))
f.close()
Copy after login

如果出现:

Compression requires the (missing) zlib module
Copy after login

解决方法:

yum install zlib zlib-devel
Copy after login

,然后重新编译安装python

 以上就是使用Python读写及压缩和解压缩文件的示例的内容,更多相关内容请关注PHP中文网(www.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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

See all articles