Python的文件操作

读操作

file = open('测试文件',mode='r',encoding='utf-8')
print(file.read())

写操作

file = open('测试文件',mode='w',encoding='utf-8')
file.write('	测试内容')                    # 这里的写入操作都会先将内容清空,再重新进行写入;并且支持转义字符的使用
file.close()

追加操作

file = open('测试文件',mode='a',encoding='utf-8')
file.write('
	测试内容2')                 # 这里的写入操作并不会清空内容,并且同样支持转义符的使用
file.close( )

读写操作

file = open('测试文件',mode='r+',encoding='utf-8')
print(file.read())                          # read会从按照最小字符内容光标位置进行查看
file.write('
测试内容3')                   #  这里的写入操作并不会清空内容,但是不支持转义字符的使用
file.close()

写读操作

file = open('测试文件',mode='w+',encoding='utf-8')
file.write('
测试内容4')                    # 这里会先覆盖原有内容再进行写入操作,支持转义字符的使用
print(file.read())                         # 这里并不会打印任何内容,因为写入之后光标已经到了结尾
file.close()

追加写入

file = open('测试文件', mode='a+', encoding='utf-8')
file.write('
测试内容5')                   #  这里的写入操作并不会清空内容,但是不支持转义字符的使用
file.read()                            # 这里并不会打印任何内容,因为写入之后光标已经到了结尾
file.close()

调节光标位置

file = open('测试文件', mode='w+', encoding='utf-8')
file.write('测试内容7')
file.seek(0)                              # seek方法是按照字节进行偏移
print(file.read())

指定光标内容打印

file = open('测试文件', mode='w+', encoding='utf-8')
file.write('测试内容8')
file.seek(0)
print(file.read(4))                          #从光标位置开始打印后面4个字符,切记这里是字符,并不是字节,即最小可视单位

获取当前光标位置,主应用于断点续传

file = open('测试文件', mode='w+', encoding='utf-8')
file.write('测试内容8')
file.seek(0)
tell = file.tell()                          # 获取光标位置
print(tell)

判断文件权限

s=open("t1.txt",mode="r+",encoding="utf-8")
print(s.readable())
print(s.writable())
s.close()

自动关闭文件句柄

with open('测试文件', mode='w+', encoding='utf-8') as file:
    file.write('测试内容9')
    file.seek(0)
    print(file.read())

以行为单位的读取

with open('测试文件', mode='r', encoding='utf-8') as file:
    print(file.readline())                      # read方法会先将整个文件缓存到内存中,再进行操作

每一行当成列表中的一个元素,添加到list中

with open('测试文件', mode='w+', encoding='utf-8') as file:
    file.write('测试内容10
测试内容11')
    file.seek(0)
    print(file.readlines())                         # 连带换行符都一并加载出来

文本内容的剪切

with open('测试文件', mode='r+', encoding='utf-8') as file:
    file.truncate(2)                                # 仅保留第一行前两个字节

文件的重命名及删除

import os
os.rename('用户文件','用户文件1')       # 重命名文件
os.remove('用户文件1')                  # 删除文件

注意事项

  • 文件本身是无法修改的
  • 文件的默认操作是'读取'
  • 文件只能通过重命名的方式修改文件内容
原文地址:https://www.cnblogs.com/guge-94/p/10406613.html