search
HomeBackend DevelopmentPython TutorialExamples of reading, writing, compressing and decompressing files using Python

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

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

文件的打开方式:

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

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

文件的属性

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

文件的读写方法:

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]) #把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。

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

一些例子:

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

压缩和解压缩文件(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()

仔细观察压缩以后的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()

如果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()

如果出现:

Compression requires the (missing) zlib module

解决方法:

yum install zlib zlib-devel

,然后重新编译安装python

 以上就是使用Python读写及压缩和解压缩文件的示例的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement
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
Explain the performance differences in element-wise operations between lists and arrays.Explain the performance differences in element-wise operations between lists and arrays.May 06, 2025 am 12:15 AM

Arraysarebetterforelement-wiseoperationsduetofasteraccessandoptimizedimplementations.1)Arrayshavecontiguousmemoryfordirectaccess,enhancingperformance.2)Listsareflexiblebutslowerduetopotentialdynamicresizing.3)Forlargedatasets,arrays,especiallywithlib

How can you perform mathematical operations on entire NumPy arrays efficiently?How can you perform mathematical operations on entire NumPy arrays efficiently?May 06, 2025 am 12:15 AM

Mathematical operations of the entire array in NumPy can be efficiently implemented through vectorized operations. 1) Use simple operators such as addition (arr 2) to perform operations on arrays. 2) NumPy uses the underlying C language library, which improves the computing speed. 3) You can perform complex operations such as multiplication, division, and exponents. 4) Pay attention to broadcast operations to ensure that the array shape is compatible. 5) Using NumPy functions such as np.sum() can significantly improve performance.

How do you insert elements into a Python array?How do you insert elements into a Python array?May 06, 2025 am 12:14 AM

In Python, there are two main methods for inserting elements into a list: 1) Using the insert(index, value) method, you can insert elements at the specified index, but inserting at the beginning of a large list is inefficient; 2) Using the append(value) method, add elements at the end of the list, which is highly efficient. For large lists, it is recommended to use append() or consider using deque or NumPy arrays to optimize performance.

How can you make a Python script executable on both Unix and Windows?How can you make a Python script executable on both Unix and Windows?May 06, 2025 am 12:13 AM

TomakeaPythonscriptexecutableonbothUnixandWindows:1)Addashebangline(#!/usr/bin/envpython3)andusechmod xtomakeitexecutableonUnix.2)OnWindows,ensurePythonisinstalledandassociatedwith.pyfiles,oruseabatchfile(run.bat)torunthescript.

What should you check if you get a 'command not found' error when trying to run a script?What should you check if you get a 'command not found' error when trying to run a script?May 06, 2025 am 12:03 AM

When encountering a "commandnotfound" error, the following points should be checked: 1. Confirm that the script exists and the path is correct; 2. Check file permissions and use chmod to add execution permissions if necessary; 3. Make sure the script interpreter is installed and in PATH; 4. Verify that the shebang line at the beginning of the script is correct. Doing so can effectively solve the script operation problem and ensure the coding process is smooth.

Why are arrays generally more memory-efficient than lists for storing numerical data?Why are arrays generally more memory-efficient than lists for storing numerical data?May 05, 2025 am 12:15 AM

Arraysaregenerallymorememory-efficientthanlistsforstoringnumericaldataduetotheirfixed-sizenatureanddirectmemoryaccess.1)Arraysstoreelementsinacontiguousblock,reducingoverheadfrompointersormetadata.2)Lists,oftenimplementedasdynamicarraysorlinkedstruct

How can you convert a Python list to a Python array?How can you convert a Python list to a Python array?May 05, 2025 am 12:10 AM

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Can you store different data types in the same Python list? Give an example.Can you store different data types in the same Python list? Give an example.May 05, 2025 am 12:10 AM

Python lists can store different types of data. The example list contains integers, strings, floating point numbers, booleans, nested lists, and dictionaries. List flexibility is valuable in data processing and prototyping, but it needs to be used with caution to ensure the readability and maintainability of the code.

See all articles

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.