Home Backend Development Python Tutorial python file operation api

python file operation api

Feb 27, 2017 pm 05:05 PM
python File operations

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))
Copy after login

输出结果:

程序运行耗时: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()
Copy after login

读文件的写法

#读文件的写法:
#读文本文件: 
input = open('data', 'r')#第二个参数是默认的,可以不加
#读二进制文件: 
input = open('data', 'rb')
#读取所有文件内容:
open('xxoo.txt').read()
#读取固定字节
open('abinfile', 'rb').read(100)
#读每行
file_object.readlines()
Copy after login


更多python 文件操作api相关文章请关注PHP中文网!

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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)

Hot Topics

Java Tutorial
1671
14
PHP Tutorial
1276
29
C# Tutorial
1256
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.

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.

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.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

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".

See all articles