利用Python进行文件读写

这篇博客介绍了Python中的文件操作,包括路径表示、读取文件、不同编码方式如ANSI和UTF-8,以及如何将爬取的POI数据存储为txt并转化为JSON。还讲解了pickle模块的使用,用于实现数据的序列化和反序列化,实现对象的持久化存储。
摘要由CSDN通过智能技术生成

一 文件对象声明与基本操作

1 路径的表示
# 双斜杠
path1 = "C:\\Users\\lizheying\\Desktop\\ziliao\\test.txt"

# 反斜线
path2 = "C:/Users/lizheying/Desktop/ziliao/text.txt"

# 使用r
path3 = r"C:\Users\lizheying\Desktop\ziliao\text.txt"

print(path1)
print(path2)
print(path3)
C:\Users\lizheying\Desktop\ziliao\test.txt
C:/Users/lizheying/Desktop/ziliao/text.txt
C:\Users\lizheying\Desktop\ziliao\text.txt
2 读取文件
# 读取文件,open语句

f = open(path1,"r")
print(type(f))
print(f)
print(f.read())
print("读取完毕")
# open("路径","模式","encoding = "编码") 如果有中文,需要添加编码格式utf8
# 模式: r:读取文件,默认:w:写入,rw:读取+写入,a:追加
# 简单的读取方法:.read()读取后,光标将会留在读取末尾
print("二次读取")
print(f.read())
print("二次读取完毕")
# 运行一次.read()之后,光标位于末尾,再次读取输出为空

f.seek(0)# 光标重新回到某个位置
print("三次读取")
print(f.read())
print("三次读取完毕")

f.close()
print("四次读取")
print(f.read()) # 关闭后无法读取


<class '_io.TextIOWrapper'>
<_io.TextIOWrapper name='C:\\Users\\lizheying\\Desktop\\ziliao\\text.txt' mode='r' encoding='cp936'>
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.

读取完毕
二次读取

二次读取完毕
三次读取
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.

三次读取完毕
四次读取
--------------------------------------------------
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值