Home > Backend Development > Python Tutorial > What are the unified steps used by Python for file operations?

What are the unified steps used by Python for file operations?

青灯夜游
Release: 2022-12-30 11:13:48
Original
6369 people have browsed it

The unified steps adopted by Python for file operations are: "Open-Operation-Close". "Open-Operation-Close" is a unified step, in which "Close" can be omitted. Python can use the methods in the os module and shutil module to operate files and folders.

What are the unified steps used by Python for file operations?

#The operating environment of this tutorial: Windows 7 system, Python 3 version, Dell G3 computer.

The unified steps adopted by Python for file operations are: ‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪

A. Operation—Read—Write

B. Open—Read—Write—Close

C. Open-read-write-write

D. Open-operate-close

Correct answerD

python file and folder operations

1. os that are often used when operating files and folders in python Common methods for modules and shutil modules.

1. Get the current working directory, that is, the directory path where the current Python script works: os.getcwd()
2. Return all files and directory names in the specified directory: os.listdir( )
3. The function is used to delete a file: os.remove()
4. Delete multiple directories: os.removedirs(r"c:\python")
5. Check the given path Whether it is a file: os.path.isfile()
6. Check whether the given path is a directory: os.path.isdir()
7. Determine whether it is an absolute path: os.path.isabs ()
8. Check whether the given path actually exists: os.path.exists()
9. Return the directory name and file name of a path: os.path.split()

Example:

os.path.split('/home/swaroop/byte/code/poem.txt')
Copy after login

Result:

('/home/swaroop/byte/code',
'poem.txt')
Copy after login

10. Split extension: os.path.splitext()
11. Get path name: os.path.dirname( )
12. Get the file name: os.path.basename()
13. Run the shell command: os.system()
14. Read and set environment variables: os.getenv() with os .putenv()
15. Gives the line terminator used by the current platform: os.linesep Windows uses '\r\n', Linux uses '\n' and Mac uses '\r'
16. Instructions The platform you are using: os.name For Windows it is 'nt' and for Linux/Unix users it is 'posix'
17. Rename: os.rename(old, new)
18 .Create a multi-level directory: os.makedirs(r"c:\python\test")
19. Create a single directory: os.mkdir("test")
20. Get file attributes: os.stat( file)
21. Modify file permissions and timestamp: os.chmod(file)
22. Terminate the current process: os.exit()
23. Get the file size: os.path.getsize(filename )

2. Comprehensive file operation methods

1.os.mknod("test.txt") Create an empty file
2.fp = open(" test.txt",w) Directly open a file, if the file does not exist, create the file
3. About open mode:

  • w: Open in writing mode,
    a: Open in append mode (start with EOF, create new file if necessary)
    r: Open in read-write mode
    w: Open in read-write mode (see w)
    a: Open in read-write mode Open (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 Open in 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]) #size为读取的长度,以byte为单位
fp.readline([size]) #读一行,如果定义了size,有可能返回的只是一行的一部分
fp.readlines([size]) #把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长,也就是说可能只读到文件的一部分。
fp.write(str) #把str写到文件中,write()并不会在str后加上一个换行符
fp.writelines(seq) #把seq的内容全部写到文件中(多行一次性写入)。这个函数也只是忠实地写入,不会在每行后面加上任何东西。
fp.close() #关闭文件。python会在一个文件不用后自动关闭文件,不过这一功能没有保证,最好还是养成自己关闭的习惯。 如果一个文件在关闭后还对其进行操作会产生ValueError
fp.flush() #把缓冲区的内容写入硬盘
fp.fileno() #返回一个长整型的"文件标签"
fp.isatty() #文件是否是一个终端设备文件(unix系统中的)
fp.tell() #返回文件操作标记的当前位置,以文件的开头为原点
fp.next() #返回下一行,并将文件操作标记位移到下一行。把一个file用于for … in file这样的语句时,就是调用next()函数来实现遍历的。
fp.seek(offset[,whence]) #将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的,一般为正数。但如果提供了whence参数就不一定了,whence可以为0表示从头开始计算,1表示以当前位置为原点计算。2表示以文件末尾为原点进行计算。需要注意,如果文件以a或a+的模式打开,每次进行写操作时,文件操作标记会自动返回到文件末尾。
fp.truncate([size]) #把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。如果size比文件的大小还要大,依据系统的不同可能是不改变文件,也可能是用0把文件补到相应的大小,也可能是以一些随机的内容加上去。

三、目录操作方法大全

1.创建目录

os.mkdir("file")
Copy after login

2.复制文件:

shutil.copyfile("oldfile","newfile") #oldfile和newfile都只能是文件
shutil.copy("oldfile","newfile") #oldfile只能是文件夹,newfile可以是文件,也可以是目标目录
Copy after login

3.复制文件夹:

shutil.copytree("olddir","newdir") #olddir和newdir都只能是目录,且newdir必须不存在
Copy after login

5.重命名文件(目录)

os.rename("oldname","newname") #文件或目录都是使用这条命令
Copy after login

6.移动文件(目录)

shutil.move("oldpos","newpos")
Copy after login

7.删除文件

os.remove("file")
Copy after login

8.删除目录

os.rmdir("dir") #只能删除空目录
shutil.rmtree("dir") #空目录、有内容的目录都可以删
Copy after login

9.转换目录

os.chdir("path") #换路径
Copy after login

四、文件综合操作实例

将文件夹下所有图片名称加上'_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 张图片
Copy after login

更多计算机编程相关知识,请访问:编程视频!!

The above is the detailed content of What are the unified steps used by Python for file operations?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source: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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template