文件的读和写(Python)
- 读文件
- 循环读取文件内容
- 写文件
- 序列化
- 反序列化
- 实例
- 读取图片
注意:文件夹和文件名是n,x,t,r,v,b等开头,会被转义的。但是大写可以,具体有哪些可以查查Python转义字符。
因为写路径的时候,文件夹与文件名之间是用斜杠连接的,而斜杆加上开头的字母(n,x,a等)会被编译为转义字符,从而出现错误。下图就可看出字体有轻微变化。或者写路径时用双斜杠。
不同模式打开文件的完全列表:
总结一下:
读文件
# 输出到控制台(这将会输出文件所有内容)
# 打开一个文件
f = open("D:\yuan\daye\jishu.txt","r")
a=f.read()
print(a)
# 关闭打开的文件
f.close()
循环读取文件内容
文件内容 | 原代码 | 添加 -2 |
文件内容有多个空行,那么代码中的 lines 列表就会有多个 ‘\n’
path = './zifu.txt'
with open(path, 'r', encoding='utf-8') as file:
for line in file:
print(line[:-2])
with open(path) as f:
line = f.readline()
while line:
print(line, end='')
line = f.readline()
fr = open(path, 'r', encoding='utf-8')
lines = fr.readlines()#读取全部内容
for line in lines:
print(line[:-2])
fr.close()
f = open(path,encoding='utf-8')
while True:
line = f.readline()
if line:
print (line[:-2])
else:
break
f.close()
个人笔记
fp = open("D:\yuan\daye\jishu.txt","r")
# 默认情况下 read是一字节一字节的读 效率比较低
a=fp.read()
print(a)
# readline是一行一行的读取 但是只能读取一行
b = fp.readline()
print(b)
# readlines 可以按照行来读取 但是会将所有的数据都读取到,并且以一个列表的形式返回
c = fp.readlines()
print(c)
fp.close()
读取一个csv文件
import pandas as pd
df = pd.read_csv('D:\yuan\daye\StatisticsGame.csv',header=None)
print(df)
'''
# 输出a时,将会一个字符一个字符的输出
# 就算将数据写入列表li。li也只会是一个一维数组,而且一个字符占一位,无法看到原文件的具体信息
li=[]
a = open(r"D:\yuan\daye\StatisticsGame.csv","r").read()
print(a)
'''
写文件
w,打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。如果目录出错会报错,因为它不会创建文件夹。
a,打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
w是内容覆盖,a是在尾部追加内容。
# 往文件里写入两行内容,
# 打开一个文件
f = open("D:\yuan\daye\jishu.txt","w")
f.write("Python 是一个非常好的语言。\n是的,的确非常好!!\n")
# 关闭打开的文件
f.close()
将【qwe.txt】文件里的内容写入到【one.sql】里
fr = open("D:\yuan\daye\qwe.txt","r")
s = fr.read()
fw = open("D:\yuan\daye\one.sql","w")
for i in s:
# i代表s的一个字符,包括换行符合
# 如果print(i) 可以看到输出结果是,一行一个字符,看到空行代表原文件内容里的空格或换行
fw.write(i)
# 关闭打开的文件
fr.close()
fw.close()
将D盘的两个文件Test1,Test2的内容合并到Test中:
def read(fileA,file):
fa = open(fileA,"r")
content = fa.read()
f = open(file, "a")
# 当目标文件有内容且光标就跟在内容之后时。先来一个换行符可以让待会输入的内容重新起一行
f.write("\n")
for i in content:
f.write(i)
fa.close()
f.close()
read("D:\Test1.txt","D:\Test.txt")
read("D:\Test2.txt","D:\Test.txt")
# 另外一种等效结果
def read(filename):
f = open(filename,"r+")
a = f.read()
return a
s = list("".join(read("E:\Test1.txt")+"\n"+read("E:\Test2.txt")))
s1 = "".join(s)
t = open("E:\Test.txt","a")
t.write(s1)
t.close()
'''
暂时不懂其中差异
s = read("E:\Test1.txt")+"\n"+read("E:\Test2.txt")
t = open("E:\Test.txt","a")
t.write(s)
t.close()
'''
序列化
将列表,字典等写入文件中。需要引入json模块
import json
fp = open("F:\Temp\img\jishu.txt","w")
name_list = ['daye','dama','dashu']
names = json.dumps(name_list) # 将name_list变为字符串
fp.write(names)
# 上面的两行等价于 json.dump(name_list,fp)
fp.close()
反序列化
将json的字符串编变成一个python对象
import json
fp = open("F:\Temp\img\jishu.txt","r")
a = fp.read()
res = json.loads(a) # 将json字符串变成python对象
# 上面的两行等价于 res=json.load(fp)
print(a)
print(type(a))
fp.close()
实例
生成一个六位数的密码本
# 生成一个六位数的密码本
import itertools as its
#引入迭代器的模块
words_num = "1234567890"
words_letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
# 生成六位数,也就是从 111111,111112,111113... 到 000000
r = its.product(words_num, repeat=6)
dic = open("E:\pass.txt", "a")
for i in r:
# i的类型是元组,里面是一个个独立的数字字符,例:('1','1','1','1','1','1')
# print("".join(i)) 打印111111,111112,111113这类字符串
dic.write("".join(i))
dic.write("".join("\n"))
dic.close()
将“记得多喝热水”这六个字,写入到E盘的Book.txt这一文件里。一共写入100行。
words = "记得多喝热水"
fw = open("E:\Book.txt", "a")
for i in range(100):
fw.write(words)
fw.write("\n")
fw.close()
统计单词出现的次数
# 统计单词出现的次数
hell="hello everyone,I'm a freshman.hello freshman,welcome to our class.everyone is perfect."
hell = hell.replace(","," ").replace("."," ")
str = hell.split()
#str=['hello', 'everyone', "I'm", 'a', 'freshman', 'hello', 'freshman', 'welcome', 'to', 'our', 'class', 'everyone', 'is', 'perfect']
liebiao = {}
# 控制台输出
for i in str:
liebiao[i] = liebiao.get(i,0)+1
print(liebiao)
# 将结果写入到文件
fw = open("D:\BaiduNetdiskDownload\jishu.txt","w")
for j in liebiao:
fw.write("{} {}\n".format(j, liebiao[j]))
fw.close()
读取图片
这里有个重要的库是skimage,安装时需要找scikit-image
from skimage import io
import matplotlib.pyplot as plt
img=io.imread('F:\Vue\kool.jpg')
io.imshow(img)
plt.show()