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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Google AI announces Gemini 1.5 Pro and Gemma 2 for developers Google AI announces Gemini 1.5 Pro and Gemma 2 for developers Jul 01, 2024 am 07:22 AM

Google AI has started to provide developers with access to extended context windows and cost-saving features, starting with the Gemini 1.5 Pro large language model (LLM). Previously available through a waitlist, the full 2 million token context windo

How to download deepseek Xiaomi How to download deepseek Xiaomi Feb 19, 2025 pm 05:27 PM

How to download DeepSeek Xiaomi? Search for "DeepSeek" in the Xiaomi App Store. If it is not found, continue to step 2. Identify your needs (search files, data analysis), and find the corresponding tools (such as file managers, data analysis software) that include DeepSeek functions.

How do you ask him deepseek How do you ask him deepseek Feb 19, 2025 pm 04:42 PM

The key to using DeepSeek effectively is to ask questions clearly: express the questions directly and specifically. Provide specific details and background information. For complex inquiries, multiple angles and refute opinions are included. Focus on specific aspects, such as performance bottlenecks in code. Keep a critical thinking about the answers you get and make judgments based on your expertise.

How to search deepseek How to search deepseek Feb 19, 2025 pm 05:18 PM

Just use the search function that comes with DeepSeek. Its powerful semantic analysis algorithm can accurately understand the search intention and provide relevant information. However, for searches that are unpopular, latest information or problems that need to be considered, it is necessary to adjust keywords or use more specific descriptions, combine them with other real-time information sources, and understand that DeepSeek is just a tool that requires active, clear and refined search strategies.

How to program deepseek How to program deepseek Feb 19, 2025 pm 05:36 PM

DeepSeek is not a programming language, but a deep search concept. Implementing DeepSeek requires selection based on existing languages. For different application scenarios, it is necessary to choose the appropriate language and algorithms, and combine machine learning technology. Code quality, maintainability, and testing are crucial. Only by choosing the right programming language, algorithms and tools according to your needs and writing high-quality code can DeepSeek be successfully implemented.

How to use deepseek to settle accounts How to use deepseek to settle accounts Feb 19, 2025 pm 04:36 PM

Question: Is DeepSeek available for accounting? Answer: No, it is a data mining and analysis tool that can be used to analyze financial data, but it does not have the accounting record and report generation functions of accounting software. Using DeepSeek to analyze financial data requires writing code to process data with knowledge of data structures, algorithms, and DeepSeek APIs to consider potential problems (e.g. programming knowledge, learning curves, data quality)

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

See all articles