The operation of files and folders (file operation functions) in python requires the os module and shutil module.
Get the current working directory, that is, the directory path where the current Python script works: os.getcwd()
Return all files and directory names in the specified directory: os.listdir()
Function used to delete a file: os.remove()
Delete multiple directories: os.removedirs(r "c:\python")
Check whether the given path is a file: os. path.isfile()
Check whether the given path is a directory: os.path.isdir()
Judge whether it is an absolute path: os.path.isabs()
Check whether the given path is a directory Really save: os.path.exists()
Return the directory name and file name of a path: os.path.split() eg os.path.split('/home/swaroop/byte/code/poem.txt ') Result: ('/home/swaroop/byte/code', 'poem.txt')
Split extension: os.path.splitext()
Get path name: os.path.dirname()
Get file name: os.path.basename()
Run shell command: os.system()
Read and set environment variables: os.getenv() and os.putenv()
Gives the line terminator used by the current platform: os.linesep Windows uses '\r\n', Linux uses '\n' and Mac uses '\r'
Indicates the platform you are using: os.name For Windows , it is 'nt', and for Linux/Unix users it is 'posix'
Rename: os.rename(old, new)
Create multi-level directories: os.makedirs(r"c:\ python\test")
Create a single directory: os.mkdir("test")
Get file attributes: os.stat(file)
Modify file permissions and timestamps: os.chmod(file)
Terminate the current process: os.exit()
Get the file size: os.path.getsize(filename)
File operation:
os.mknod("test .txt") Create an empty file
fp = open("test.txt",w) Open a file directly. If the file does not exist, create the file
About open mode:
w Open in write mode,
a Open in append mode (start from EOF, create a new file if necessary)
r+ Open in read-write mode
w+ Open in read-write mode ( See w )
a+ Open in read-write mode (see a )
rb Open in binary read mode
wb Open in binary write mode (see w )
ab Open in binary append mode (see a )
rb+ Open in binary read-write mode (see r+ )
wb+ Open in binary read-write mode (see w+ )
ab+ Open in binary read-write mode (see a+ )
fp.read([size]) Part
fp.readlines([size]) # Treat each line of the file as a member of a list, and return this list. In fact, it is implemented internally by calling readline() in a loop. If the size parameter is provided, size represents the total length of the read content, which means that only a part of the file may be read.
fp.write(str) #Write str to the file, write() will not add a newline character after str
fp.writelines(seq) (Multiple lines written at once). This function also just writes faithfully, without adding anything after each line.
fp.close() #Close the file. Python will automatically close a file after it is no longer used. However, this function is not guaranteed. It is best to develop the habit of closing it yourself. If a file is operated on after it is closed, a ValueError will be generated. "File Tag"
fp.isatty() The beginning is the origin
fp. Next () #Return to the next line and move the file operation mark to the next line. When a file is used in a statement such as for...in file, the next() function is called to implement traversal.
fp.seek(offset[,whence]) #Move the file operation mark to the offset position. This offset is generally calculated relative to the beginning of the file, and is generally a positive number. But this is not necessarily the case if the whence parameter is provided. whence can be 0 to start calculation from the beginning, and 1 to calculate from the current position as the origin. 2 means the calculation is performed with the end of the file as the origin. It should be noted that if the file is opened in a or a+ mode, the file operation mark will automatically return to the end of the file every time a write operation is performed.
fp.truncate([size]) #Cut the file to the specified size. The default is to cut to the position of the current file operation mark. If size is larger than the file size, depending on the system, the file may not be changed, the file may be padded to the corresponding size with 0, or some random content may be added.
目录操作:
os.mkdir("file") 创建目录
复制文件:
shutil.copyfile("oldfile","newfile") oldfile和newfile都只能是文件
shutil.copy("oldfile","newfile") oldfile只能是文件夹,newfile可以是文件,也可以是目标目录
复制文件夹:
shutil.copytree("olddir","newdir") olddir和newdir都只能是目录,且newdir必须不存在
重命名文件(目录)
os.rename("oldname","newname") 文件或目录都是使用这条命令
移动文件(目录)
shutil.move("oldpos","newpos")
删除文件
os.remove("file")
删除目录
os.rmdir("dir")只能删除空目录
shutil.rmtree("dir") 空目录、有内容的目录都可以删
转换目录
os.chdir("path") 换路径
相关例子
1 将文件夹下所有图片名称加上'_fc'
python代码:
# -*- coding:utf-8 -*- import re import os import time #str.split(string)分割字符串 #'连接符'.join(list) 将列表组成字符串 def change_name(path): global i if not os.path.isdir(path) and not os.path.isfile(path): return False if os.path.isfile(path): file_path = os.path.split(path) #分割出目录与文件 lists = file_path[1].split('.') #分割出文件与文件扩展名 file_ext = lists[-1] #取出后缀名(列表切片操作) img_ext = ['bmp','jpeg','gif','psd','png','jpg'] if file_ext in img_ext: os.rename(path,file_path[0]+'/'+lists[0]+'_fc.'+file_ext) i+=1 #注意这里的i是一个陷阱 #或者 #img_ext = 'bmp|jpeg|gif|psd|png|jpg' #if file_ext in img_ext: # print('ok---'+file_ext) elif os.path.isdir(path): for x in os.listdir(path): change_name(os.path.join(path,x)) #os.path.join()在路径处理上很有用 img_dir = 'D:\\xx\\xx\\images' img_dir = img_dir.replace('\\','/') start = time.time() i = 0 change_name(img_dir) c = time.time() - start print('程序运行耗时:%0.2f'%(c)) print('总共处理了 %s 张图片'%(i))
输出结果:
程序运行耗时:0.11
总共处理了 109 张图片
Python常见文件操作示例
os.path 模块中的路径名访问函数
分隔
basename() 去掉目录路径, 返回文件名
dirname() 去掉文件名, 返回目录路径
join() 将分离的各部分组合成一个路径名
split() 返回 (dirname(), basename()) 元组
splitdrive() 返回 (drivename, pathname) 元组
splitext() 返回 (filename, extension) 元组
信息
getatime() 返回最近访问时间
getctime() 返回文件创建时间
getmtime() 返回最近文件修改时间
getsize() 返回文件大小(以字节为单位)
Query
exists() Whether the specified path (file or directory) exists
isabs() Whether the specified path is an absolute path
isdir() Whether the specified path exists and is a directory
isfile( ) specifies whether the path exists and is a file
islink() specifies whether the path exists and is a symbolic link
ismount() specifies whether the path exists and is a mount point
samefile() two path names Whether it points to the same file
os.path.isdir(name): Determine whether name is a directory. If name is not a directory, return false
os.path.isfile(name): Determine whether name is a directory File, if name does not exist, it will return false
os.path.exists(name): Determine whether the file or directory name exists
os.path.getsize(name): Get the file size, if name is a directory, return 0L
os.path.abspath(name): Get the absolute path
os.path.normpath(path): Normalize the path string format
os.path.split(name): Split the file name and directory (fact , if you use directories entirely, it will also split the last directory as a file name, and it will not determine whether the file or directory exists)
os.path.splitext(): Separate file names and extensions
os.path.join(path,name): Connect directory with file name or directory
os.path.basename(path): Return file name
os.path.dirname(path): Return file path
File operations in the os module:
os module properties
linesep String used to separate lines in the file
sep String used to separate file path names
pathsep A string used to separate file paths
curdir The string name of the current working directory
pardir (The string name of the parent directory of the current working directory)
1. Rename: os. rename(old, new)
2. Delete: os.remove(file)
3. List the files in the directory: os.listdir(path)
4. Get the current working directory: os.getcwd()
5. Change the working directory: os.chdir(newdir)
6. Create a multi-level directory: os.makedirs(r"c:\python\test")
7. Create Single directory: os.mkdir("test")
8. Delete multiple directories: os.removedirs(r"c:\python") #Delete all empty directories under the last directory of the given path.
9. Delete a single directory: os.rmdir("test")
10. Get file attributes: os.stat(file)
11. Modify file permissions and timestamps: os.chmod(file)
12. Execute operating system commands: os.system("dir")
13. Start a new process: os.exec(), os.execvp()
14. Execute the program in the background: osspawnv( )
15. Terminate the current process: os.exit(), os._exit()
16. Split file name: os.path.split(r"c:\python\hello.py") -- > ("c:\\python", "hello.py")
17. Split extension: os.path.splitext(r"c:\python\hello.py") --> (" c:\\python\\hello", ".py")
18. Get the path name: os.path.dirname(r"c:\python\hello.py") --> "c:\ \python"
19. Get the file name: os.path.basename(r"r:\python\hello.py") --> "hello.py"
20. Determine whether the file exists: os .path.exists(r"c:\python\hello.py") --> True
21. Determine whether it is an absolute path: os.path.isabs(r".\python\") --> ; False
22. Determine whether it is a directory: os.path.isdir(r"c:\python") --> True
23. Determine whether it is a file: os.path.isfile(r"c :\python\hello.py") --> True
24. Determine whether it is a link file: os.path.islink(r"c:\python\hello.py") --> False
25. Get the file size: os.path.getsize(filename)
26.**********: os.ismount("c:\\") --> True
27. Search All files in the directory: os.path.walk()
Operations of the shutil module on files:
1. Copy a single file: shultil.copy(oldfile, newfle)
2 .Copy the entire directory tree: shultil.copytree(r".\setup", r".\backup")
3. Delete the entire directory tree: shultil.rmtree(r".\backup")
临时文件的操作:
1.创建一个唯一的临时文件:tempfile.mktemp() --> filename
2.打开临时文件:tempfile.TemporaryFile()
内存文件(StringIO和cStringIO)操作
[4.StringIO] #cStringIO是StringIO模块的快速实现模块
1.创建内存文件并写入初始数据:f = StringIO.StringIO("Hello world!")
2.读入内存文件数据:print f.read() #或print f.getvalue() --> Hello world!
3.想内存文件写入数据:f.write("Good day!")
4.关闭内存文件:f.close()
import os import os.path import unittest import time #import pygame class PyFileCommonOperatorTest(unittest.TestCase): def __init__(self): """constructor""" def test01(self): print os.linesep print os.sep print os.pathsep print os.curdir print os.pardir print os.getcwd() print 'unittest here' if __name__ == "__main__": t = PyFileCommonOperatorTest() t.test01()
读文件的写法
#读文件的写法: #读文本文件: input = open('data', 'r')#第二个参数是默认的,可以不加 #读二进制文件: input = open('data', 'rb') #读取所有文件内容: open('xxoo.txt').read() #读取固定字节 open('abinfile', 'rb').read(100) #读每行 file_object.readlines()
更多python 文件操作api相关文章请关注PHP中文网!