基本的文件操作代码、注释

基本的文件操作代码、注释。

import os

# 在所在文件夹中,创建一个文件:hdy.txt
file = open("hdy.txt", "w")
# 对文件写入内容
file.write("hdy is a handosme boy !")
# 读取文件内容,并打印出来
with open("hdy.txt", "r") as file:
    string = file.read() # 读取文件里面全部信息;如果file.read(20),则读取20个字符内容
    print(string)

# 路径拼接成 data/test.jpg
path1 = os.path.join('data/','test.jpg')
print(path1)

# 显示指定路径文件夹中所有文件
all_file = os.listdir("F:\\PyQt_Serial_Assistant_Drive_Detect\\Smart Video Clock System\\")
print(all_file)

# 分割函数os.path.spilt()
path2 = "data/2.hdy.6.jpg"

test = os.path.split(path2)  # 将"data/2.hdy.6.jpg"中斜杠分割
print(test)

path3 = "data/3.hdy.6.jpg"
test1 = os.path.split(path3)[1].split(".")[0]  # 将path3在分割线隔开,选择[1]即得到”3.hdy.6.jpg“,然后再按点分割,选择[0]得到3
test2 = os.path.split(path3)[1].split(".")[1]  # 将path3在分割线隔开,选择[1]即得到”3.hdy.6.jpg“,然后再按点分割,选择[1]得到hdy
print(test1,"\n", test2)

文件列表列表

在这里插入图片描述

运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/K_AAbb/article/details/127132674