一、字符编码
字符编码: 在文件存/取/Python3解释器解释的时候,字符发生的一种变换,例如a->00001111.
存
从内存到硬盘的时候是存
取
从硬盘到内存的时候是取
name = 'nick'
Python3解释器解释
在python3解释器解释的时候,会新开辟一块内存空间放入变量,python3会把name='nick'以unicode的形式生成一个变量.print(name)
字符编码
硬盘中躺了各个国家的代码,要想在计算机上运行使用,在内存中必须使用Unicode的编码,因为Unicode能和硬盘中各个国家的二进制中的代码进行转换》》》》》》》》》取
但Unicode的编码会占用额外的内存,所以会将Unicode的编码简化成UTF-8储存进硬盘,(UTF-8只是简化了代码的存储,它并不能与其他国家硬盘中的代码进行关系转换。)》》》》》》》》存
import sys
sys.getdefaultencoding()
'utf-8'
二、文件处理
打开文件#不用 open() & 一次性全读了 read()
fr = open(r"D:\桌面\梗.txt",encoding='UTF-8')
print(fr.read())
print(fr.read(),1)
眼:划走吧
脑子:在听会
手:那我没事刷会评论区
1
读一行,读完了就空 readline()
fr = open(r"D:\桌面\梗.txt",encoding='UTF-8')
print(fr.readline())
print(fr.readline())
print(fr.readline())
眼:划走吧
脑子:在听会
手:那我没事刷会评论区
关闭文件close()
python对文件的操作是基于操作系统的
fr = open(r"D:\桌面\梗.txt",encoding='UTF-8')
fr.close()# 不仅删除了变量名f,并且也关闭了文件,这时候文件对操作系统也是关闭状态的
打开后自动关闭 with open (文件路径,打开模式rt/wt/at/rb/wb/ab,编码格式) as 变量名,\open(...):
with open(r"D:\桌面\梗.txt",'r',encoding='UTF-8') as fr:
data = fr.read()
print(data)
kanacianukanacianu114514114514
写入write() #mode = 'w',会清空原文件内容
fw = open(r"D:\桌面\梗.txt",encoding='UTF-8',mode='w')
fw.write('114514')
fr = open(r"D:\桌面\梗.txt",encoding='UTF-8')
print (fr.read())
114514
三、文件的三种打开方式
+t&b
r模式是默认模式,文本模式
b模式是通用的模式,因为所有的文件在硬盘中都是以二进制的形式存储的,需要注意的是:b模式读写文件,一定不能加上encoding参数,因为二进制无法再编码。
f = open(r"D:\桌面\梗.txt",encoding='UTF-8',mode='a')
f.write('kanacianu')
r
r: read,只读模式,只能读不能写,文件不存在时报错。
w
w: 只能写,不能读,文件存在的时候会清空文件(打开时)后再写入内容;文件不存在的时候会创建文件后写入内容。
a
a: 只能写,不能读,可以追加。文件存在,则在文件的末端写入内容;文件不存在的时候会创建文件后写入内容。
f = open(r"D:\桌面\梗.txt",encoding='UTF-8',mode='a')
f.write('114514')
6
print(r'1111\n')#特殊字符不生效
1111\n
四、路径
绝对路径
Windows系统绝对路径从盘符(C:\、D:\)开始写一个完整的路径。
macos系统从根目录(/Users)开始写一个完整的路径。
相对路径
相对于当前执行文件所在的文件夹开始找。
import sys
print(sys.path)
['C:\\Users\\86178', 'D:\\anaconda3\\python312.zip', 'D:\\anaconda3\\DLLs', 'D:\\anaconda3\\Lib', 'D:\\anaconda3', '', 'D:\\anaconda3\\Lib\\site-packages', 'D:\\anaconda3\\Lib\\site-packages\\win32', 'D:\\anaconda3\\Lib\\site-packages\\win32\\lib', 'D:\\anaconda3\\Lib\\site-packages\\Pythonwin', 'D:\\anaconda3\\Lib\\site-packages\\setuptools\\_vendor']
五、文件的高级应用
可读、可写 #不太用
r+: 可读、可写#不会清空
w+: 可写、可读#打开时会清空
a+: 可追加、可读#不会清空
with open(r"D:\桌面\梗.txt", 'w+t', encoding='utf-8') as fw:
print(fw.readable())
print(fw.writable())
True
True
文件内指针移动
偏移(字节个数,位置)seek(offset,whence)
with open(r"D:\桌面\梗.txt", 'r', encoding='utf-8') as fw:
print(fw.read())
with open(r"D:\桌面\梗.txt", 'r+', encoding='utf-8') as fw:
fw.seek(4, 0)# 0相当于文件头开始;1相当于当前文件所在位置;2相当于文件末尾
fw.write('你好')
with open(r"D:\桌面\梗.txt", 'r', encoding='utf-8') as fw:
print(fw.read())
1231161
6
9199651
1231你好
9199651
'你好'替换了161\n6
光标所在位置 tell()
with open(r"D:\桌面\梗.txt", 'r+', encoding='utf-8') as fw:
fw.seek(4, 0)
print(fw.tell())
4
清空n个字节后的文件 truncate(n)
with open(r"D:\桌面\梗.txt", 'r+', encoding='utf-8') as fw:
print(fw.read())
print('')
with open(r"D:\桌面\梗.txt", 'r+', encoding='utf-8') as fw:
fw.truncate(5)
print(fw.read())
12312189415
16484651696
21661516486
12312
六、文件修改的方式
读取内容,将内容修改后存入新文件删除原文件,将新文件重命名为原文件
将硬盘存放的该文件的内容全部加载到内存,在内存中是可以修改的,修改完毕后,再由内存覆盖到硬盘(word,vim,nodpad++等编辑器)。#文件太大会卡
import os
with open('37r.txt') as fr, \
open('37r_swap.txt', 'w') as fw:
data = fr.read() # 全部读入内存,如果文件很大,会很卡
data = data.replace('tank', 'tankSB') # 在内存中完成修改
fw.write(data) # 新文件一次性写入原文件内容
# 删除原文件
os.remove('37r.txt')
# 重命名新文件名为原文件名
os.rename('37r_swap.txt', '37r.txt')
将硬盘存放的该文件的内容一行一行地读入内存,修改完毕就写入新文件,最后用新文件覆盖源文件。
import os
with open('37r.txt') as fr,\
open('37r_swap.txt', 'w') as fw:
# 循环读取文件内容,逐行修改
for line in fr:
line = line.replace('jason', 'jasonSB')
# 新文件写入原文件修改后内容
fw.write(line)
os.remove('37r.txt')
os.rename('37r_swap.txt', '37r.txt')
print('done...')
文件只需要记住
-
with open(filename,mode,encoding) as file:
file+操作 -
rt/rb/wt/at
-
文件的复制
group = [11,22,33,44,55,66,77,88,99,90]
zidian ={'k1':[],'k2':[]}
for i in group:
if i > 66:
zidian['k1'].append(i)
elif i < 66:
zidian['k2'].append(i)
print(zidian)
{'k1': [77, 88, 99, 90], 'k2': [11, 22, 33, 44, 55]}
s='hello jason tank tank jason sean say hello dsb dsb sb'
lis = s.split()
lis1 = []
for i in lis:
if i not in lis1:
lis1.append(i)
dic = dict.fromkeys(lis1)
for i in dic:
dic[i] = lis.count(i)
print(dic)
{'hello': 2, 'jason': 2, 'tank': 2, 'sean': 1, 'say': 1, 'dsb': 2, 'sb': 1}
s='hello jason tank tank jason sean say hello dsb dsb sb'
lis = s.split()
dic = dict()
for i in lis:
if i in dic:
dic[i]+=1
elif i not in dic:
dic[i]=1
print(dic)
{'hello': 2, 'jason': 2, 'tank': 2, 'sean': 1, 'say': 1, 'dsb': 2, 'sb': 1}
data = []
dic = dict()
with open(r"D:\桌面\a.txt", 'r', encoding='utf-8') as fr,\
open(r"D:\桌面\a1.txt", 'w', encoding='utf-8') as fw:
for i in fr:
name = i.split()[0]
dic[name]=i.split()[1:]
print(dic)
{'apple': ['10', '3'], 'tesla': ['100000', '1'], 'mac': ['3000', '2'], 'lenovo': ['30000', '3'], 'chicken': ['10', '3']}
i_price = 0
with open(r'D:\桌面\a.txt','r',encoding='utf-8') as fr:
for i in fr:
i_list = i.strip().split()
i_price += int(i_list[1])*int(i_list[2])
print(i_price)
196060
user_name = {}
ifo = {}
with open(r'D:/桌面/user_info.txt','r',encoding='utf-8') as ur:
for i in ur:
user_name = i.split(':')[0]
ifo[user_name] = i.split(':')[1].strip('\n')
import random
while 1:
username = input('请输入你的帐号:')
if username not in ifo:
print('该账号不存在,开始注册')
password = input('请输入你的密码:')
with open(r'D:/桌面/user_info.txt','a',encoding='utf-8') as fa:
fa.write(f'\n{username}:{password}')
else:
password = input('请输入你的密码:')
if password == ifo[username]:
print('密码正确!')
break
else:
print('密码错误')
print(f'欢迎{username}!')
correct_age = 27#random.randint(1,100)
count = 0
prize_dict = {}
while 1:
age1 = input('猜猜我的年龄:D 》》》》》').strip()
count += 1
if age1.isdigit():
age = int(age1)
if age > correct_age:
print('猜大了!')
elif age == correct_age:
print('猜对了!')
with open(r'D:\桌面\a.txt','r',encoding='utf-8') as fr:
for k,v in enumerate(fr):
prize = v.split()[0]
prize_dict[k] = prize
print(prize_dict)
choose = int(input('选个奖品吧!'))
print(f'你选择了{prize_dict[choose]}!')
with open(r'D:/桌面/winner.txt.txt','a',encoding='utf-8') as fa:
fa.write(f'{username}:{prize_dict[choose]}')
break
elif age < correct_age:
print('猜小了!')
else:
print('请好好填')
if count == 3:
choice = input('还玩不?')
if choice == 'Y':
count = 0
elif choice == 'N':
break
请输入你的帐号: Lunar
请输入你的密码: 1354
密码正确!
欢迎Lunar
猜猜我的年龄:D 》》》》》 27
猜对了!
{0: 'apple', 1: 'tesla', 2: 'mac', 3: 'lenovo', 4: 'chicken'}
选个奖品吧! 1
你选择了tesla!
prize_dict = {}
with open(r'D:\桌面\a.txt','r',encoding='utf-8') as fr:
for k,v in enumerate(fr):
prize = v.split()[0]
prize_dict[k] = prize
print(prize_dict)
{0: 'apple', 1: 'tesla', 2: 'mac', 3: 'lenovo', 4: 'chicken'}
遍历序列(如列表、元组、字符串)时同时获取元素索引和值 enumerate()
浙公网安备 33010602011771号