Python directory and file operations (detailed)

basic file operations

ptyhon has a built-in file object. When using a file object, you can use the built-in open() method to create a file object, and then perform some basic operations on the file object.

File creation and closing

file = open(filename, mode='w', buffering=None, encoding=None)
 
# 参数说明
# file : 创建的文件对象
 
# filename : 要创建或者打开的文件名,需要以引号(单双都行,必须是英文的,还要加后缀)括起来,如打开或创建"name.txt"文件
 
# mode : 用于打开文件的模式,如 'w'是写入
 
# buffering : 用于指定读写文件的缓冲模式,默认为缓冲模式,
# buffering = False 表示不缓冲
# buffering = 数字(大于1) 表示缓冲大小
 
# encoding : 默认GBK编码打开文件,如果文件不是GBK编码会报错
# 大家可以指定编码打开文件 一般是常用'utf-8'编码

8f69e40ee4084fb0b9bb54a2ded1e5ef.png#pic_center

在这里插入代码片# 以写入模式创建文件对象,编码为utf-8
file = open('student.txt',mode='w',encoding='utf-8')
 
# 在创建或者打开一个文件后,一定要记着关闭,避免对文件数据造成损失
# 关闭文件可用close()
file.close()

write and read files

data input

# 方法使用
file = open('student.txt',mode='w',encoding='utf-8')
file.write(string)
# string : 要写入的数据
 
 
data = '人生苦短,我学python'
file = open('data.txt',mode = 'w', encoding = 'utf-8')
file.write(data)
file.close()
 
# 一定要注意!!!
# 写入文件后一定要用close()方法关闭,否则写入的内容会缺失
# 因为写入的内容会先进入缓存区,并没有直接写入,只有调用close()时才能保证内容全部写入
 
# 如果不想立马关闭文件,也可以用flush()方法把内容写入
# file.flush()

read data

# 方法使用
file.read(size)
# size : 读取的字符个数,如果省略则读取所有
# 读取上面写入的内容
file = open('data.txt', mode='r', encoding='utf-8')
print(file.read(5))  # 人生苦短,
 
# 把剩下的内容读取完
print(file.read()) # 我学python
file.close()
 
 
# file.seek(offset)
# offset : 用于指定移动的字符数 跟read()有所不同,utf-8编码中汉字占三个字符,GBK编码汉字占(包括中文标点符号)2
# 个字符,无论采用何种编码英文字母和数字都是按一个字符计算。
file = open('data.txt', mode='r', encoding='utf-8')
file.seek(15)  # 人生苦短,
print(file.read(3))  # 我学p
file.close()
 
# file.readline() 读取一行
file = open('data.txt', mode='r', encoding='utf-8')
file.readline() # 人生苦短,我学python
file.close()
 
# file.realines() 读取全部行 跟read()差不多,但可以遍历
data = '人生苦短,我学python\n人生苦短,我学python'
 
file = open('data.txt', mode='w', encoding='utf-8')
file.write(data)
 
# 可以遍历
file = open('data.txt', mode='r', encoding='utf-8')
for i in file.readlines():
    print(i)
file.close()
 
 
 

Use of the with context manager

Sometimes, after we open a file, we may forget to close it, which may cause our data loss and security problems. In order to avoid such problems, you can use the with statement provided by python, and the context manager will close the opened file regardless of whether an exception occurs.

# with open(file_name,mode,encoding) as f:
#   	f.write(string) # 执行读写的操作
# 其实没有什么变化 只增加了一个自动打开和关闭文件的操作
# as 表示重命名 
 
data = '人生苦短,我学python'
 
# 写入数据
with open('data.txt', mode='w', encoding='utf-8') as g:
    g.write(data)
 
# 读取数据
with open('data.txt', mode='r', encoding='utf-8') as f:
    print(f.read())
 
# 追加数据
with open('data.txt', mode='a', encoding='utf-8') as n:
    n.write(data)
 
 
 
 
 
 

Here to remind everyone to pay attention to the mode of file opening! ! !
The mode of mode Note! ! !
r Read a file, the file must exist, otherwise an error will be reported
a Add new content to the back of the content If the file exists, add it If it does not exist, create a file and add it
w Write content If the file exists, there is content in the file, the original content will be replaced by the new content Overwrite, create a file if it does not exist and then write

Relative Paths vs. Absolute Paths

Before introducing the operation of the os module, let’s talk about the file path first. What is a path?
In the computer, our files will be stored in the disk, such as D:\Typora\resources\appsrc\editor, which is the storage path of a file. A slash "\" is often used to separate each section, and the slash is followed by the previous sub item.

  • Relative path The
    relative path refers to the path relationship with other files (or folders) caused by the path where this file is located. For example, there is a directory total, and the file student.txt is saved in this directory, then we can pass "total \student.txt" to open this file, the relative path is relative to a certain file, and it is variable.
    In python, "\" is a special character and needs to be escaped. Two backslashes "\" are equal to one backslash "\". Of course, we can also use "r" to escape, use "r" in front of the string, such as r"total\student.txt"
with open(r'total\student.txt',mode='w',encoding='utf-8') as f:
   f.write(data)
  • Absolute path
    The absolute path is easy to understand, it is the path where the file is stored, usually starting from the drive letter, such as D:\Thunder\Profiles\DownloadData, starting from the drive letter and going directly to the target file.

os module operation directory

In python, the built-in module os and the submodule os.path are used to operate directories and files. When using the os module, remember to import it.
5f21031b42b9487d80747cad63ba6f70.png#pic_center

7574ffa8bf374bf79736aa42691a1028.png#pic_center

Create directory and path concatenation

  • Create a directory
import os
 
# mkdir(name) name为要创建的文件名
# 文件存在就会报错
os.mkdir('name')
  • Create multi-level directories
import os
 
# makedirs(path1\path2......) 要\\ 或者字符串前面加r
os.makedirs(r'name\name1\name2')
os.makedirs('names\\names1\\names2')
 

5fe8e537d988480d99f59ba07886bb8c.png#pic_center

  • path stitching
import os.path
 
# os.path.join(name1,name2...) 如果有多个盘符开头的路径 以最后的为准
# 拼接不会检查路径是否有效
name1 = 'D:\\Users\\wo\\top'
name2 = 'names'
print(os.path.join(name1, name2))
# D:\Users\wo\top\names
 
name3 = 'C:\\u'
name4 = 'name2'
print(os.path.join(name1, name2, name3, name4))
# C:\u\name2
 

Get the absolute path of a directory or file

  • Returns the current file path
import os
 
# getcwd()返回当前文件的绝对路径
print(os.getcwd())
 
  • Get the absolute path of the specified file or directory
import os.path
 
# os.path.abspath(name) name 获取的文件名
print(os.path.abspath('names'))
 
# C:\Users\政\Desktop\文件夹操作\names

Determine whether the path of a file or directory is valid

import os.path
 
# os.path.isdir(name) name为文件名 相对与绝对路径都行
print(os.path.isdir('names'))
 
# os.path.isfile(name) name为文件名 相对与绝对路径都行
print(os.path.isfile('data.txt'))
 

Determine whether the file exists and get all the file names in the specified directory

  • Determine whether the file exists
import os.path
# 先创建目录
os.mkdir('name')
 
# 判断目录或文件是否存在 存在返回True 不存在返回False
# 相对与绝对路径都可以
print(os.path.exists('name'))
  • Get all file names in the specified directory
import os
 
# 获取当前目录的路径
file_add = os.getcwd()
 
# os.listdir(path) 
# 获取指定目录下的所有文件
print(os.listdir(file_add))
 

Delete directories and files

 
import os
 
# 先创建目录
os.mkdir('name')
os.makedirs('name1\\name2\\name3')
 
# 再删除目录
# os.rmdir(name) name为目录名
os.rmdir('name')
 
# 删除多级目录
# os.removedirs(path1\path2......)
os.removedirs('name1\\name2\\name3')
 

Rename files and directories

import os
 
# 创建目录
os.mkdir('name')
 
# 在目录name中创建文件name1
with open('name\\name1', mode='w') as f:
    f.write('a')  # 写入字符串'a'
 
# os.rename(str,dst) str要重命名的文件 dst要命名的文件名字
# 重命名目录
os.rename('name', 'student')
os.rename('student\\name1', 'student1')
 

traverse directory

import os
 
# 创建一个根目录
os.mkdir('a')
# 在根目录创建3个在目录
for i in range(3):
    os.mkdir(f'a\\name{
      
      i}')
    # 在每一个子目录创建3个文件
    for k in range(0, 3):
        with open(f'a\\name{
      
      i}\\' + f'age{
      
      k}.txt', mode='w') as f:
            f.write('')
 
# os.path.walk(top,topdown)
# top 指定遍历的目录
# topdown 用与指定遍历的顺序,如果值为True 则优先遍历根目录(自上而下)
# 如果值为False,先从最后一级目录开始(自下而上) 默认为True
 
for g in os.walk('a'):
    print('路径:', g[0])
    print('目录名:', g[1])
    print('文件名:', g[2])
 

other operations

  • Separate filenames from extensions
import os.path
 
# os.path.splitext() 分离文件名与扩展名
 
name = 'file.txt'
print(os.path.splitext(name))
  • Extract filenames from a directory
import os.path
 
# os.path.basename(path) path 为目录路径
 
name = 'name\\file.txt'
print(os.path.basename(name))
 
  • Extract the file path from a path, excluding the filename
import os.path
 
# os.path.dirname(path) path 为目录路径
 
name = 'name\\file.txt'
print(os.path.dirname(name))
 

Summarize

This article writes about using the built-in function open in python to create read-write files, using the built-in module os to create files, directories and some basic operations on files and directories, and using with to automatically open and close files. In normal practice, you can practice a lot, you don't have to memorize all these methods, just check and practice more, and you will naturally memorize them all. If there are any mistakes in the article, please correct me. Finally, thank you everyone!

Guess you like

Origin blog.csdn.net/qq_65898266/article/details/124875850