Python基础-文件操作

                                  Python基础-文件操作

1.文件的打开和关闭

# 1.打开文件
# 默认r模式  只读  文件不存在,报错
# f = open('a.txt')

# w模式  写权限
# 如果文件不存在,就会创建文件
# 如果文件存在的话,就会覆盖原来的文件
# f = open('b.txt',mode='w')
# 如果r模式  打开存在的文件 不会覆盖
# f = open('b.txt',mode='r')

# a可以创建文件 不会覆盖文件
# f = open('b.txt',mode='a')


# r+ 读写 不能创建  不能覆盖
# f = open('b.txt',mode='r+')

# w+ 读写  创建  覆盖
# f = open('b.txt',mode='w+')


# 读写  创建 不会覆盖
f = open('b.txt',mode='a+')


# 2.关闭文件
f.close()

文件的属性和方法:

# 1.打开文件
f = open('b.txt','a+')
# 获取文件名
# print(f.name)
# 获取访问模式
# print(f.mode)
# 判断文件是否关闭
# print(f.closed)

# 是否可读写
# print(f.readable())
# print(f.writable())
# 文件编码
# print(f.encoding) # gbk  utf-8

# 2.关闭文件
f.close()
# print(f.closed)

文件写入:

# 1.打开文件
f = open('b.txt','w')
"""------------------ write ------------------"""
# 2.文件写入
# f.write('hello world')
# f.write('hello world')
"""------------------ writelines ------------------"""
l = ['bill','gates','tom']
f.writelines(l)
# 3.关闭文件
f.close()

文件的读取:

# 1.打开文件
f = open('b.txt','r')
# 2.文件读取
"""------------------ read ------------------"""
# 将文件中所有的内容读取出来
# result = f.read()
# read有参数n 默认值-1 代表读取整个文件内容 指定读取个数 \n也算一个字符
# result = f.read(15)
# print(result)

"""------------------ readline ------------------"""
# 读取一行
# readline有参数 limit 默认值-1 代表读取整行 可以指定读取的个数 个数超过行的字符数据 读取整行
# result = f.readline(15)
# print(result)
"""------------------ readlines ------------------"""
# 读取整个文件  返回列表  列表中每一个元素代表一行数据
# result = f.readlines()
# print(result)
# 3.文件关闭
f.close()

文件备份制作:

"""
需求:
输入文件的名字,然后程序自动完成对文件进行备份

分析:
1.输入文件名 b.py
2.创建文件  文件名[复制].py
3.读取文件,写入到复制的文件中
"""
# 1.输入文件名 b.txt
inputName = input('请输入文件名')
# 2.创建文件  文件名[复制].py
# inputName.find()
# inputName.rfind()
index = inputName.rfind('.')
copyName = inputName[:index] + '[复制]' +inputName[index:]
# print(inputName)
# print(copyName)
# 3.读取文件,写入到复制的文件中
# 打开源文件
inputFile = open(inputName)
# 打开复制的文件
copyFile = open(copyName,'w')

"""------------------ 读写 ------------------"""
# 读取整个文件内容
# content = inputFile.read()
# 内容写入到复制的文件中
# copyFile.write(content)

"""------------------ 读取一部分写入 ------------------"""
# line = inputFile.readline()
# while line:
#     # 有数据,写入文件
#     copyFile.write(line)
#     # 读取一行
#     line = inputFile.readline()

"""------------------ read(limit) ------------------"""

# 关闭文件
inputFile.close()
copyFile.close()

统计代码练习:

"""
需求:
输入一个文件名,统计文件中代码行数、注释行数、空行数
并输出代码以及注释

分析:
1.输入文件名 test.py
2.打开文件
3.统计 readline
    空行 空
    注释行数 去空格 #开头
    代码行数

"""
# 1.输入文件名 test.py
fileName = input('请输入要统计的文件名')
# 2.打开文件
f = open(fileName,encoding='utf-8')
# 3.统计 readline
#     空行 空
#     注释行数 去空格 #开头
#     代码行数

# 定义三个变量保存空行  注释行数  代码行数
emptyCount = 0
commandCount = 0
codeCount = 0

"""------------------ readlines ------------------"""
# while True:
# resultL = f.readlines()
# for line in resultL:
#     if not line.strip():
#         emptyCount += 1
#     elif line.strip().startswith('#'):
#         commandCount += 1
#     else:
#         codeCount += 1
"""------------------ readline ------------------"""
line = f.readline()
# str = '  '
while line:
    if not line.strip():
        emptyCount += 1
    elif line.strip().startswith('#'):
        commandCount += 1
    else:
        codeCount += 1

    # 读取下一行
    line = f.readline()

print('代码数:%d,空行数:%d,注释数:%d'%(codeCount,emptyCount,commandCount))
# 4.关闭文件
f.close()

文件的定位读写:

f = open("123.txt", "a+")
"""------------------ 获取指针位置 ------------------"""
# 获取当前指针位置
# index = f.tell()
# print(index)
"""------------------ seek偏移指针读取 ------------------"""
# 从文件开头,偏移5个字节
# f.seek(5,0)
# f.seek(3,2)
"""------------------ a和a+模式 ------------------"""
f.seek(0,0)
content = f.read()

"""------------------ a ------------------"""

print(content)
f.close()

f = open("123.txt", "w+")
f.write("hello world")
content = f.read()
print(content)
f.close()

绝对路径和相对路径:

# 第一个参数:文件路径
# f  = open('D:\gg.txt')
# f  = open('./a.txt')
# f  = open('a.txt')
# 打开files下的a.txt
# ./ ..
f  = open('./files/a.txt')

编码和解码:

# 创建a.txt
f = open('d.txt','w',encoding='utf-8')
print(f.encoding)
# 写入数据
f.write('中国')

# 关闭
f.close()

# f = open('b.txt')
# content = f.read()
# print(content)
# f.close()

文件的其它操作:

import os
"""------------------ 文件重命名 ------------------"""
# os.rename('a.txt','aa.txt')

"""------------------ 删除文件 ------------------"""
# os.remove('aa.txt')

"""------------------ 创建文件夹 ------------------"""
# os.mkdir('aa')

"""------------------ 删除文件夹 ------------------"""
# os.removedirs('aa')
"""------------------ 获取当前文件夹路径 ------------------"""
# 返回绝对路径
# path = os.getcwd()
# print(path)
"""------------------ 获取当前的目录列表 ------------------"""
# 列举出给定的目录下所有的文件以及文件夹 文件夹下的文件不会列举
# result = os.listdir('.')
# print(result)
"""------------------  ------------------"""

通用路径操作:

import os.path
"""------------------ 获取绝对路径 ------------------"""
# print(os.path.abspath('a.txt'))

"""------------------ 获取文件名 ------------------"""
# print(os.path.basename('D:\\codespace\\python4\\Day06\\a.txt'))
"""------------------ 获取文件夹路径 ------------------"""
# print(os.path.dirname('D:\\codespace\\python4\\Day06\\a.txt'))
"""------------------ 判断文件或文件夹是否存在 ------------------"""
# print(os.path.exists('D:\\codespace\\python4\\Day06\\b.txt'))
# f = open('g.txt','r')
"""------------------ 获取文件大小 ------------------"""
# print(os.path.getsize('D:\\codespace\\python4\\Day06\\b.txt'))

"""------------------ 拼接路径 ------------------"""
# print(os.path.join('D:\\codespace\\python4\\Day06', 'a.txt'))

"""------------------ 路径分割 ------------------"""
# print(os.path.split('D:\\codespace\\python4\\Day06\\a.txt'))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_无往而不胜_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值