- 1.文件路径
- 1.1 不同系统环境下的路径
- 1.2 当前工作目录
- 1.3 绝对路径和相对路径
- 1.4 新建文件夹—— os.makedirs()
- 2.文件的读写
- 2.1 打开文件
- 2.2 读写文件
- 3.文件的操作
- 3.1 shutil模块简介
- 3.2 删除文件
- 3.3 遍历目录树 os.walk(dir)
- 3.4 zipfile模块——操作压缩文件
1. 文件路径
1.1 不同系统环境下的路径
不同系统的文件分隔符可能会不同,Window下,使用""作为文件分隔符,OS 和Linux下使用"/",在处理文件的时候,必须处理这中情况。
- 使用os.path.sep 来获取文件分隔符
- 使用os.path.join()来获取路径。
得到:import os path = os.path.join("dir1", "dir2", "dir3", "file1") print path path2 = os.path.join("user/bin/python", "newFile") print path2
dir1/dir2/dir3/file1
user/bin/python/newFile
1.2 当前工作目录
每个运行在计算机上的程序,都有一个“当前工作目录”,或cwd。所有没有从根文件夹开始的文件名或路径,都假定在当前工作目录下。利用os.getcwd()函数,可以取得当前工作路径的字符串,并可以利用os.chdir()改变它。
>>> import os
>>> os.getcwd()
'/Users/chelsea/Documents/workspace/test/src/mcx/basePython'
>>> os.chdir('/Users/chelsea/Documents/workspace/test/src/mcx/test')
>>> os.getcwd()
'/Users/chelsea/Documents/workspace/test/src/mcx/test'
os.chdir(newPath) newPath必须是已存在的路径,否则会抛出异常:OSError: [Errno 2] No such file or directory
1.3 绝对路径和相对路径
- 绝对路径:从根文件夹开始
- 相对路径:相对于当前工作目录开始
- (.)、(..) 文件夹:不是真正的文件夹,(.)表示该目录的缩写,(..) 表示符文件夹。如,当前目录'/Users/chelsea/Documents/workspace/test/src/mcx/basePython', 目录下有test.py文件,则可以表示为.\test.py; "..\test"表示文件夹'/Users/chelsea/Documents/workspace/test/src/mcx/test'。
1.4 新建文件夹—— os.makedirs()
import os
os.makedirs('/Users/chelsea/Documents/workspace/test/src/mcx/newfolder')
os.path模块常用方法
- os.path.abspath(path) 回参数的绝对路径的字符串。
- os.path.isabs(path),是否是一个绝对路径。
- os.path.relpath(path,start) 返回相对start的相对路径的字符串。如果没有提供start,就使用当前工作目录作为开始路径。
- os.path.dirname(path) 返回路径字符串(最后一个/前的文字)。
- os.path.basename(path) 返回文件名(最后一个/后的文字)。
- os.path.split(calcFilePath) 获取路径和文件名,返回一个元组,元组有两个值,第一个值为路径,第二个值为文件名。
- os.path.getsize(path) 获取文件大小。
- os.path.exists(path) 文件是否存在。
- os.path.isfile(path) 是否是文件
- os.path.isdir(path) 是否是文件夹
- os.listdir(path) 获取 path下的文件列表。返回一个列表,值为文件名。
2. 文件的读写
在Python中,读写文件有3个步骤:
- 调用open()函数,返回一个File对象。
- 调用File对象的read()或write()方法。
- 调用File对象的close()方法,关闭该文件。
2.1 打开文件
- open(path) 以只读的方式打开文件,若文件不存在抛出异常:IOError: [Errno 2] No such file or directory。不可以写入数据。
- open(path, "r") 同上。
- open(path, "w") 以只写的方式打开文件,若文件则创建文件。读数据抛出异常:IOError: File not open for reading
mode char | 含义 |
---|---|
'r' | open for reading (default) |
'w' | open for writing, truncating the file first |
'x' | open for exclusive creation, failing if the file already exists |
'a' | open for writing, appending to the end of the file if it exists |
'b' | binary mode |
't' | text mode (default) |
'+' | open a disk file for updating (reading and writing) |
'U' | universal newlines mode (deprecated) |
path = '/Users/chelsea/Documents/workspace/test/test.txt';
file = open(path)
2.2 读写文件
- file.read() 将文件内容看成是单个大字符串,改方法返回这个字符串。
- file.readlines() 返回一个列表,列表的每个元素是文件的每一行。
- file.write(content)
shelve模块保存变量
shelve模块可以将程序中的变量保存到数据库中。
- 保存数据:
import shelve # 将会在运行目录下产生一个mcxconfig.db configFile = shelve.open('mcxConfig') configFile['name'] = 'machenxi' configFile.close()
- 读取数据
import shelve configFile = shelve.open('mcxConfig') print configFile['name']
pprint.pformat()保存变量
import 语句导入的模块本身也是Python脚本,可以使用pprint.pformat()来保存一个Python脚本,以便在其他Python程序中使用。
写入:
import pprint
cats=[{'name':'Zophie','desc':'chubby'},{'name':'Pooka','desc':'fluffy'}]
pprint.pformat(cats)
fileObj=open('myCats.py','w')
fileObj.write('cats='+pprint.pformat(cats)+'\n')
fileObj.close()
读取:
import myCats
priny(myCats.cats)
运行结果: [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]
3. 文件的操作
3.1 shutil模块简介
使用shutil模块,可以对文件进行复制、移动、改名、删除。
- shutil.copy(source, destination) 将路径source处的文件复制到路径destination处的文件夹,返回新的路径。(复制单个文件)
- shutil.copyTree(source, destination) 复制整个文件夹,返回新的路径。
- shutil.move(source, destination) 移动文件夹,返回新的路径,有重名文件,旧文件会被覆盖。destination可以是一个文件路径,移动后文件将被重命名;destination是文件夹路径时必须存在,否则会异常。
3.2 删除文件
3.2.1 永久删除文件
- os.unlink(path) 删除path处文件。
- os.rmdir(path) 删除path处的文件夹,文件夹必须为空。
- shutil.rmtree(path) 删除path文件,包含的文件夹和文件都会被删除。
3.2.2 send2trash模块——把文件放到回收站
import send2trash
send2trash.send2trash(path)
3.3 遍历目录树 os.walk(dir)
os.walk(dir) os.walk()函数可以用于for循环语句,遍历目录树,就像使用range()函数遍历一个范围的数字一样。
os.walk()在循环的每次迭代中,返回3个值:
1.当前文件夹名称的字符串。(是指for循环当前迭代的文件夹)
2.当前文件夹中子文件夹的字符串的列表。
3.当前文件夹中文件的字符串的列表。
程序的当前工作目录,不会因为os.walk()而改变。
import os
for folderName, subfolders, filenames in os. walk(' C:\\ delicious'):
print(' The current folder is ' + folderName)
for subfolder in subfolders:
print(' SUBFOLDER OF ' + folderName + ': ' + subfolder)
for filename in filenames:
print(' FILE INSIDE ' + folderName + ': '+ filename) print('')
3.4 zipfile模块——操作压缩文件
3.4.1 读取ZIP文件
import zipfile, os
exampleZip = zipfile.ZipFile('example.zip')
exampleZip.namelist() # 获取所有文件夹以及文件夹下的字符串列表 ['spam.txt', 'cats/', 'cats/catnames. txt', 'cats/zophie.jpg']
spamInfo = exampleZip. getinfo(' spam. txt')
spamInfo.file_ size # 获取文件实际大小
spamInfo.compress_size # 获取文件压缩后的大小
exampleZip. close()
3.4.3 解压缩ZIP文件
import zipfile, os
exampleZip = zipfile.ZipFile('example.zip') # 解压到当前工作目录
exampleZip = zipfile.ZipFile('example.zip', destinationPath) # 解压到指定目录
exampleZip.extractall()
exampleZip. close()
3.4.3 压缩ZIP文件
import zipfile
newZip = zipfile. ZipFile('new.zip', 'w') # 'w'模式会覆盖new.zip文件里的内容,若要内new.zip中添加一个文件,使用'a'。
newZip.write('spam.txt', compress_type= zipfile.ZIP_ DEFLATED)
newZip.close()