文件的基本操作

发布时间 2023-12-05 15:36:28作者: Formerly0^0

文件的基本操作

1. 操作文件打开的两种方式

# 1.文件的操作方式一:
# 讲文件以指定编码格式打开,讲文件句柄赋值给变量fp
fp = open('01.txt', 'w', encoding='utf-8')
# 把hello写入文件
fp.write("hello")
# 关闭文件
fp.close()

2.文件的操作方式二:
# Python解释器内置了一个文件操作器 --- 能自主的回收系统资源 --- with 语句
# 打开with open() as fp 打开文件,赋值fp。自动关闭
with open('01.txt', 'w', encoding='utf-8') as fp:
    fp.write("world")

2. 文件操作的三种方式

# 操作文件的三种方式 w、a、r

# w write 模式:write 覆盖写模式,如果你文件中有内容,直接覆盖原内容写入新的内容
# 如果文件不存在,则创建一个新的文件,然后再像文件中写新的内容进去
with open ('01.txt','w',encoding='utf-8') as fp:
    fp.write("覆盖了原有的world")
    
 
# a(append) 模式 : write 追加写模式,如果你文件中有内容,再原有内容的基础上追加内容
# 如果不存在该文件,则会创建一个新的文件,然后再向文件中写新的内容进去
with open('01.txt', 'w', encoding='utf-8') as fp:
    fp.write("world")
    
  
# r(read) 模式 : read 读内容模式,可以将文件中的内容读出来
with open('01.txt','r',encoding='utf-8') as fp:
    data = fp.read()
    print(data) # 覆盖了原有的world追加了了world后面

3. 控制文本的读写格式

# t 模式 : 文本类型。读内容和写内容都是字符串格式
data = "hello world"
with open('01.txt','wt',encoding='utf-8') as fp:
    fp.write(data)
# 读出来的内容是字符串格式,即使长得像列表,其实也是字符串格式    
   
# b 模式 :二进制模式。读内容和写进去的内容必须都是二进制格式,b模式下不需要指定编码格式
with open('image-20201022211946339.png','rb') as fp:
    data = fp.read()
    print(data)
  

4. 文件拷贝联系

# # 编写文件拷贝工具
# # 输入一个文件地址 --- 把文件内容读出来
# # 输入一个文件地址 --- 把当前文件内容拷贝到新的地址和新的文件里面
path_start = input("请输入原地址:").strip()
path_end = input("请输入新地址:").strip()
with open(path_start, 'rb') as path_r, open(path_end, 'wb') as path_w:
    path_w.write(path_r.read())


# /Users/chenxu/Documents/pythonProjects28/day10/image-20201022211946339.png
# 新地址:/Users/chenxu/Documents/pythonProjects28/day10/img/image-2020102221194633.png

5.文件操作详细方法

  • read,读

    • 读所有

      with open('01.txt','r',encoding='utf-8')as fp:
        data = fp.read()
        print(data) 
      # hello world
      # 我的名字叫serein
      
    • readline,读一行

      with open('01.txt','r',encoding='utf-8')as fp:
        data = fp.readline()
        print(data)
       # hello world
      
    • readlines,读所有行,放到列表里,每行作为列表的一个元素

      with open('01.txt','r',encoding='utf-8')as fp:
        data = fp.readlines()
        print(data)
      #['hello world','我的名字叫serein']
      
      

6.控制文件内光标移动

# 1.控制读的字符个数,读n个字符(字节)读出来的字符个数
with open('01.txt','r',encoding='utf-8')as fp:
  data = fp.read(2)
  print(data) # he
 
# 2.seek方法,移动光标到指定位置(字节)
# seek : 三种模式 :
# 0 : 以文件开头作为参照
# 1 : 以当前我所在位置作为参照
# 2 : 以文件末尾的位置作为参照

# 2.1 0模式:已开头为参照物
with open('01.txt','rt',encoding='utf-8')as fp:
    fp.seek(2,0) # 从开头开始算,往后移动2个字节,开始读数据
    print(fp.read()) # llo world
    
# 2.2 1模式:以当前所在位置做为参照物
with open('01.txt','rb')as fp:
    fp.seek(2,1) 
    data = fp.read()
    print(data.decode('utf-8')) 
    # llo world 
    # 我的名字叫serein
    
# 2.3 2模式:以文件末尾的位置作为参照
with open('01.txt','rb')as fp:
    fp.seek(0,2)
    print(fp.read())

7.文件替练习

# 原来的文本内容如下
# 张一蛋     山东    179    49    12344234523
# 李二蛋     河北    163    57    13913453521
# 王全蛋     山西    153    62    18651433422

# 修改后的内容如下
# 张一蛋(妇女主任)  山东    179    49    12344234523
# 李二蛋(村长)     河北    163    57    13913453521
# 王全蛋(书记)     山西    153    62    18651433422


with open('02.txt', 'r', encoding='utf-8') as fp:
    data = fp.readlines()

line_list = []

for i in data:
    if "张一蛋" in i:
        i = i.replace(i.split()[0], f"{i.split()[0]}(妇女主任)")
    elif "李二蛋" in i:
        i = i.replace(i.split()[0], f"{i.split()[0]}(村长)")
    elif "王全蛋" in i:
        i = i.replace(i.split()[0], f"{i.split()[0]}(书记)")
    line_list.append(i)
print(line_list)

with open('02.txt', 'w', encoding='utf-8') as fp:
    fp.writelines(line_list)


8.列表生成式

# 示例1
num_list = []
for i in range(10):
    num_list.append(i)
print(num_list)

# 列表生成式
num_list = [i for i in range(10)]
print(num_list)


# 示例2
test_1 = [1, 2, 3]
test_2 = [4, 5, 6]
new_list = []
for j in test_1:
    for k in test_2:
        num = j*k
        new_list.append(num)
print(new_list)

# 列表生成式 : 遍历两个列表并取出每一个列表的元素 做乘法运算
list_one = [x * y for x in test_1 for y in test_2]
print(list_one)
# [4,5,6,8,10,12,12,15,18]


num_dict = {}
for key in range(3):
    for value in range(2):
        num_dict[key] = value

print(num_dict)

my_dict = {key: value for key in range(3) for value in range(2)}
print(my_dict)
# {0: 1, 1: 1, 2: 1}

8.1 新生成列表的每个元素都可以是任意的表达式或对象

test = [1, 2, 3]

print([i * i for i in test])
# [1,4,9]

print([[i, i + 2] for i in test])
# [[1,3],[2,4],[3,5]]

8.2 让每个元素执行相同的操作

# 原始列表 : 每个元素都有空格
some_animals = [' dog', 'cat  ', ' sheep ']

# 列表生成式: 新的列表,每个元素都去除掉了空格
some_animals_new = [i.strip() for i in some_animals]
print(some_animals_new)
# ['dog','cat','sheep']

8.3 加入嵌套循环

test_1 = [1, 2, 3]
test_2 = [4, 5, 6]

# 列表生成式 : 遍历两个列表并取出每一个列表的元素 做乘法运算
list_one = [x * y for x in test_1 for y in test_2]
print(list_one)
# [4,5,6,8,10,12,12,15,18]

# 列表生成式 : 遍历两个列表并取出每一个列表的元素 做新列表的生成
list_two = [[x, x + y] for x in test_1 for y in test_2]
print(list_two)
# [[1, 5], [1, 6], [1, 7], [2, 6], [2, 7], [2, 8], [3, 7], [3, 8], [3, 9]]

###  注意通过这两个print体会谁是内层循环,谁是外层循环

# 列表生成式 : 遍历两个列表并取出每一个列表对应索引的元素 做乘法运算
list_three = [test_1[i] * test_2[i] for i in range(len(test_1))]
print(list_three)
# [4, 10, 18]

# 列表生成式 : 遍历两个列表并取出每一个列表对应索引的元素 做乘法运算
list_four = [x * y for x, y in zip(test_1, test_2)]
print(list_four)
# [4, 10, 18]

9.字典生成式

  • 语法格式如下:
{键:值 for 迭代变量 in 可迭代对象 [if 条件表达式]}
  • 案例
my_dict = {key: value for key in range(3) for value in range(2)}
print(my_dict)
# {0: 1, 1: 1, 2: 1}
  • 最常见的哪里还是下述的代码,遍历一个具有键值关系的可迭代对象。
my_tuple_list = [('name', '橡皮擦'), ('age', 18), ('class', 'no1'), ('like', 'python')]
my_dict = {key: value for key, value in my_tuple_list}
print(my_dict)
# {'name': '橡皮擦', 'age': 18, 'class': 'no1', 'like': 'python'}