【文件处理】文件(夹)的一些常用处理总结

文件(夹)的一些常用处理总结。

文件的一般读入写入总结

  • with openopen 多一个 自动 close 操作。

基本操作

函数名 操作
.read() 读取文件所有内容
.readlines() 将每行文件内容存入列表读取
.write() 写入文件

参数的问题

r r+ w w+ a a+
read O O O O
write O O O O O
create O O O O
truncate O O
position at start O O O O
position at end O O
  • truncate means delete the content of the file.

  • Some differences
    • The r throws an error if the file does not exist or opens an existing file without truncating it for reading; the file pointer position at the beginning of the file.
    • The r+ throws an error if the file does not exist or opens an existing file without truncating it for reading and writing; the file pointer position at the beginning of the file.
    • The w creates a new file or truncates an existing file, then opens it for writing; the file pointer position at the beginning of the file.
    • The w+ creates a new file or truncates an existing file, then opens it for reading and writing; the file pointer position at the beginning of the file.
    • The a creates a new file or opens an existing file for writing; the file pointer position at the end of the file.
    • The a+ creates a new file or opens an existing file for reading and writing, and the file pointer position at the end of the file.

文件(夹)不存在,则创建

  • 文件夹不存在,则创建的问题。
  • 文件(如test.txt)不存在,创建(写入)的问题。
  • 文件夹及文件都不存在,创建(写入)的问题。
    • 先创建文件夹,再创建(写入)文件。

若文件夹不存在,则创建

1
2
3
4
5
import os

def if_folder_exists(folder_path):
if not os.path.exists(folder_path):
os.makedirs(folder_path)

若文件不存在,则创建(写入)

  • 参考上文-参数的问题-w或者w+

分离路径和文件名 以及 分离文件名和后缀

1
2
3
4
5
import os

file_path = "D:/pzlu/test.py"
(filepath, tempfilename) = os.path.split(file_path) # 分离路径和文件名
(filename, extension) = os.path.splitext(tempfilename) # 分离文件名和后缀

遍历文件夹下所有文件及目录

显示目录下所有文件

1
2
3
4
5
6
7
8
import os 

g = os.walk(r"e:\test")

for path,dir_list,file_list in g:
# 文件夹路径, 文件夹名字, 文件名
for file_name in file_list:
print(os.path.join(path, file_name) )

显示所有子目录

1
2
3
4
5
6
7
import os 

g = os.walk("e:\test")

for path,dir_list,file_list in g:
for dir_name in dir_list:
print(os.path.join(path, dir_name) )