龙空技术网

36岁学习python第20天:文件读写

评评无奇打工人 788

前言:

今天姐妹们对“python读取unicode文件”大约比较珍视,兄弟们都需要剖析一些“python读取unicode文件”的相关知识。那么小编也在网摘上收集了一些关于“python读取unicode文件””的相关资讯,希望朋友们能喜欢,小伙伴们快快来学习一下吧!

文件编码

Python解释器使用的是unicode编码。

.py文件在磁盘上使用utf-8存储

文件读写

With语句

with open("test.txt", "r") as file: print(file.read())

file.readLines() 返回的是一个列表。

# 文件如果不存在会自动创建# 文件追加afile = open("test.txt", "a")file.writelines("hello,world\n")file.close()# 文件读取rfile = open("test.txt", "r")print(file.readlines())
Walk()函数

os.walk()是一种遍历目录的函数,它以一种深度优先的策略(depth-first)访问指定的目录。

其返回的是(root,dirs, files)

root代表当前遍历的目录路径,string类型

dirs代表root路径下的所有子目录名称,list类型,列表中的每个元素是string类型,代表子目录名称。

files代表root路径下的所有子文件名称,返回list类型,列表中的每个元素是string类型,代表子文件名称。

import ospath = os.getcwd()print(path)for dirpath,dirname,filename in os.walk(path):    print("root:", dirpath)    print("dir:", dirname)    print("file:", filename)

标签: #python读取unicode文件