python
第二章python一般文件操作
open函数:打开文件操作,第一个参数是文件路径,如果文件不存在,将报错。第二个参数为操作方式,是写还是读,第三个问编码方式。很多打开文件汉子乱码,就可以设置utf-8模式来让其显示正常。
示例
#打开绝对地址文件
fl=open(r'D:\\Logger\\_202008.txt','r',encoding='utf-8')
print(fl.read())
结果
open和os函数:
示例
#打开绝对地址文件
fl=open(r'D:\\Logger\\_202008.txt','r',encoding='utf-8')
print(fl.read())
import os
#查看os使用方式
print(help(os))
#获取当前路径
print(os.getcwd())
#返回路径列表类型
print(os.listdir(os.getcwd()))
os函数:用OS函数来操作文件。创建目录,创建TXT文件,然后写入内容,保存写入的内容。注:with存在自动关闭功能,所以我们这文件没有用close()方法。如果没有使用with封装的,需要操作文件后关闭。
示例
import os
#读取相对路径
path=os.getcwd()
#文件名称
filename='ts'
#创建文件,并返回相对路径
filepath=os.path.join(path,filename)
#如果文件不存在创建,存在重新创建
if not os.path.isdir(filename):
os.mkdir(filepath)
os.chdir(filepath)
#打开文件,写入内容
with open('{}.txt'.format(filename),'w',encoding='utf-8') as f:
wr=input('请输入内容,您输入的内容会保存到创建的文件里面:\n')
#将写入的内容存放到创建文件中
f.write(wr)
#f.close()
结果
读取数据用OS函数和open结合方式来操作文件。
示例
import os
#读取文件相对路径
f_path=os.getcwd()
#拼接完成路径,读取
fread = open(f_path+ '\\' + 'ts\\ts.txt', 'r', encoding='utf-8')
#获取所有数据
fcontent=fread.readlines()
#分行输出内容
for l in fcontent:
print(l,end='')
获取文件树形结构
示例
import os
#获取相对路径
path=os.getcwd()
#切换到当前路径下面
os.chdir(path)
for dirpath,names,files in os.walk(path):
#获取路径中特殊符号
l1=dirpath.replace(path,'').count(os.sep)
name_index="| "*(l1)+"|--"
files_index="| "*(l1+1)+"|--"
if not l1:
print('{}'.format(path[0]))
print('|--{}'.format(path[3:]))
else:
print('{}{}'.format(names,os.path.basename(dirpath)))
for f in files:
#打印出树图
print('{}{}'.format(files_index,f))
结果
获取文件下面所以文件
示例
import os
def fil(hh):
for roots,dirs,files in os.walk(hh):
for file in files:
print(os.path.join(roots,file))
for dir in dirs:
fil(dir)
fil('E:\python\Infrastructure\第三章')
结果
如有错误请联系更改:微信 sy157715743