day 10 -python 文件读操作

一  对文件的操作流程

step1 打开文件,得到文件句柄并赋值给一个变量

step2 通过句柄对文件进行操作

step3 关闭文件

二 读文件 ,读完后要f.close()

只读为r,默认为此模式

读整个文件内容

或者

with open("D:\\test.txt") as f :
data = f.read()
print(data)

无需执行关闭操作

 单行读取文件,只读一行,f.readline()

扫描二维码关注公众号,回复: 8153655 查看本文章

 读取多行,for ..in..默认每行有空行

除去换行符 str.strip()函数

f = open("D:\\test.txt") #读模式
data = f.readlines()
for i in data:
print(i.strip())

三 读大文件,高效率

一行一行读,只保存一行

f = open("D:\\test.txt") #读模式
for line in f:
print(line)

某一行不输出,比如第二行

f = open("D:\\test.txt") #读模式
count = 0
for line in f:
if count == 1:
print("-----分割线-----")
print(line)
count +=1

四 读文件目录 

1 os.listdir() 获取当前文件目录下的所有文件(包含文件夹)

import  os
path = "D:\\"

files = os.listdir(path)
for file in files:
print(file)

2 os.walk() 获取当前文件目录下的所有文件,包含子目录下的文件

import  os
def file_name_walk(file_dir):
for root,dirs,files in os.walk(file_dir):
print("root",root)
print("dirs",dirs)
print("files",files)

file_name_walk("D:\\")
      

  

猜你喜欢

转载自www.cnblogs.com/lucky-sunshine/p/12022884.html