博客信息

Python基础之文件常用操作

发布时间:『 2019-06-26 20:54』  博客类别:Python  阅读(740)

文件的写入操作

 

文件:

.avi

.mp4

.gif

.py

......

 

作用:

数据持久化

 

操作:

1、打开文件

(1) File=open()

 

2、//修改(文件内容操作)

(1) Write(内容)

 

3、关闭文件(自动保存)

(1) Close()

 

import locale
# 获取当前默认的编码方式(cp936),可以看成是GBK
print(locale.getpreferredencoding())

# 将字符串写入到javaxl.txt中,'w'代表写,'r'代表读,utf-8代表国际编码表,替换掉原有的编码方式
# javaxl.txt文件存在的话,会重新创建,然后覆盖原有内容
# 如果不存在的话,会创建,然后写入内容
file=open('javaxl.txt','w',encoding='utf-8')
# 如果设置'w'-->'a',那么会在原有内容上进行追加,不会覆盖
# file=open('javaxl.txt','a',encoding='utf-8')
file.write('www.javaxl.com')
file.close()


文件的读取操作

文件的读取:

Read()

以字符串的形式读取所有内容

readLine()

一次读取一行

readLines()

以列表的形式读取所有内容

def write_content(fileName):
    file=open(fileName,'a',encoding='utf-8')
    for i in range(1,5):
        content=input("请输入第%d句"%i)
        file.write('\n')
        file.write(content)
        #刷新
        file.flush()
    file.close()

# write_content('javaxl.txt')

def read_content1(fileName):
    file = open(fileName,'r',encoding='utf-8')
    content=file.read()
    # <class 'str'>
    print(type(content))
    # 将文件中的所有内容以字符串的形式输出
    print(content)
    file.close()

read_content1('javaxl.txt')

print('---------------------------')
def read_content2(fileName):
    file = open(fileName,'r',encoding='utf-8')
    content=file.readline()
    while content !='':
        content=file.readline()
        # <class 'str'>
        print(type(content))
        # 文件中的一行字符串
        print(content)
    file.close()

read_content2('javaxl.txt')

print('---------------------------')
def read_content3(fileName):
    file = open(fileName,'r',encoding='utf-8')
    content=file.readlines()
    # <class 'list'>
    print(type(content))
    # ['www.javaxl.com\n', '床前明月光\n', '疑是地上霜\n', '举头望明月\n', '低头思故乡']
    # 将每一行字符串当做列表中的一个元素,最终返回列表list
    print(content)
    file.close()

read_content3('javaxl.txt')


文件的复制操作

 

需求:

完成javaxl.txt的复制

1、打开目标文件

2、读取文件内容

3、写入新文件

新文件的名字的处理

 

4、关闭文件(读取的文件、新创建的文件)


# 待操作的文件
file_name='javaxl.txt'
# 待操作的文件存放的位置
file_dir='E:/workspace/ideaProjects/w1/pythonbase/day07/'
file_path=file_dir+file_name
# 打开目标文件
file=open(file_path,'r',encoding='utf-8')
content=file.read()

# 新文件名格式:原文件名_new.txt
index=file_name.index('.')
# javaxl
name=file_name[0:index]
# 文件后缀
suffix=file_name[index:]
# 新名字
new_file_name=name+"_new"+suffix
new_file_path=file_dir+new_file_name

# 打开新文件
new_file = open(new_file_path,'w',encoding='utf-8')
new_file.write(content)

#关闭文件
file.close()
new_file.close()


封装文件复制函数


def copy_file(file_path):
    file_split_index = file_path.rindex('/')
    # 获取文件名 javaxl.txt
    file_name = file_path[file_split_index+1:]
    # 获取所在目录    E:/workspace/ideaProjects/w1/pythonbase/day07/
    file_dir = file_path[0:file_split_index+1]

    # 打开目标文件
    file=open(file_path,'r',encoding='utf-8')
    content=file.read()

    # 新文件名格式:原文件名_new.txt
    index=file_name.index('.')
    # javaxl
    name=file_name[0:index]
    # 文件后缀
    suffix=file_name[index:]
    # 新名字
    new_file_name=name+"_new"+suffix
    new_file_path=file_dir+new_file_name

    # 打开新文件
    new_file = open(new_file_path,'w',encoding='utf-8')
    new_file.write(content)

    #关闭文件
    file.close()
    new_file.close()

copy_file('E:/workspace/ideaProjects/w1/pythonbase/day07/javaxl.txt')


文件指针偏移处理 

 

文件指针的偏移

查看光标的位置

Tell()

查看光标位置

 

光标位置手动偏移

Seek(offset,position)


file=open('javaxl.txt','r',encoding='utf-8')
print(file.tell())
# 读6个字符出来,其中换行\n也算一个字符 (www.ja)
print(file.read(6))
# 文件中光标停留在6的位置
print(file.tell())

import io
# io.SEEK_SET 0
# io.SEEK_CUR 1
# io.SEEK_END 2
# 光标偏移2
# file.seek(2,0)
file.seek(2,io.SEEK_SET)
# 从光标为2的位置读取剩下所有字符
print(file.read())
file.close()

# 从文件末尾读取6个字节
# 理解为字节的读取不需要指定编码
# ValueError: binary mode doesn't take an encoding argument
file2=open('javaxl.txt','rb')
# file2.seek(-6,2)
file2.seek(-6,io.SEEK_END)
# b'\xe6\x95\x85\xe4\xb9\xa1'
print(file2.read())
file2.close()


文件夹及文件操作的常用方法


文件:

重命名:

os.rename()

删除文件:

os.remove()

文件夹:

获取当前所在路径

os.getcwd()


修改所在文件夹

os.rename(old,new)

创建文件夹

os.mkdir(dir)

获取文件夹中所有的子文件

os.listdir()

os.listdir(dir)

判断是否为文件

os.path.isfile(fileName)

判断是否为文件夹

os.path.isdir(fileName)


import os
# os.chdir('c:/')
# 获取当前路径
# E:\workspace\ideaProjects\w1\pythonbase\day07
print(os.getcwd())
# 返回当前文件夹中所有文件列表
# ['demo1.py', 'demo2.py', 'demo3.py', 'demo4.py', 'demo5.py', 'demo6.py', 'javaxl.txt', 'javaxl_new.txt']
print(os.listdir())
# 文件重命名(文件不存在会报错    FileNotFoundError)
# os.rename('javaxl_new.txt','xiaoli.txt')
# 清空的文件不会进回收站(文件不存在会报错    FileNotFoundError)
# os.remove('xiaoli.txt')
# 当要创建的文件夹已存在会报错    FileExistsError
# os.mkdir('new_dir1')
# 这个创建的是文件夹,不是文件
# os.mkdir('new_dir2.txt')

curr_path = os.getcwd()
files=os.listdir(curr_path)
for fileName in files:
    if os.path.isfile(fileName):
        print('%s是文件'%(curr_path+"\\"+fileName))
    elif os.path.isdir(fileName):
        print('%s是文件夹'%(curr_path+"\\"+fileName))


控制台截图


小李飞刀_Python


总结:

1、操作文件内容,要通过open方法,获取文件对象才能进行操作;

2、操作文件本身,不操作内容,需要导包import os,通过os来完成一系列的操作;

 






关键字:     Python基础       文件  

备案号:湘ICP备19000029号

Copyright © 2018-2019 javaxl晓码阁 版权所有