基础的文件读写(纯文本文件)

Path()的read_text()和write_text()

from pathlib import Path
p = Path('demo.txt')
p.write_text("hello world")
# 创建并写入文档
p.read_text()
# 读取文档内容

以上是基于Path()实现对文件的基础交互,更常用的是使用open()函数。

使用open()函数处理文件

打开文件

file = open(Path.home() / 'demo.txt')  # 可以向open()传入Path对象
# 或者
file = open("C:/Users/Tom/demo.txt")   # 也可以向open()传入字符串表示的路径,此处省略了第二个参数'r',表示读取(read)。
# 返回的file是一个file对象

# 读取file对象的内容
file.read()  # 把文件的所有内容读取称一个大字符串

file.readlines()  # 把文件内容按行读取称一个列表
# 除了最后一样,其他每一行都以'\n'结束


file.close() # 使用完成后要关闭

写入文件

file = open("C:/Users/Tom/demo.txt",'w') 
file.write('hello world!\n')
file.close()

file = open("C:/Users/Tom/demo.txt",'a') 
file.write('Goodbye!')
file.close()

file = open("C:/Users/Tom/demo.txt",'r')
content = file.read()
file.close()
print(content)
# 输出:
#  hello world!
#  Goodbye!

shelve模块保存变量

使用shelve模块,可以把python的变量保存到二进制的shelf文件中。这样可以从硬盘中恢复变量的数据。

# 写入
>>> import shelve
>>> shelvefile = shelve.open('mydata')
>>> cats = ['a','b','c']
>>> shelvefile['cats']=cats
>>> shelvefile.close()
# 读取
>>> sfile = shelve.open('mydata')
>>> type(sfile)
<class 'shelve.DbfilenameShelf'>
>>> sfile['cats']
['a', 'b', 'c']
>>> sfile.close()
# shelve值同样有keys()和values()方法,类似字典。
>>> sfile = shelve.open('mydata')
>>> sfile.keys()
KeysView(<shelve.DbfilenameShelf object at 0x00000199952EF250>)
>>> sfile.values()
ValuesView(<shelve.DbfilenameShelf object at 0x00000199952EF250>)
# 传给list可查看内容
>>> list(sfile.keys())
['cats']
>>> list(sfile.values())
[['a', 'b', 'c']]
>>> sfile.close()

用pprint.format()函数保存变量

pprint.format()函数返回与pprint.pprint()同样美观的字符串内容,但不输出它。该内容不但美观,而且是语法正确的python代码。

借用此方法,可以把python代码进行保存:

>>> import pprint
>>> cats = [{'name':'Zophie','desc':'chubby'},{'name':'Pooka','des':'fluffy'}]
>>> pprint.pformat(cats)
"[{'desc': 'chubby', 'name': 'Zophie'}, {'des': 'fluffy', 'name': 'Pooka'}]"
>>> file = open('mycats.py','w')
>>> file.write('cats=' + pprint.pformat(cats) + '\n')
80
>>> file.close()
# mycats.py的内容如下:
# cats = [{"desc": "chubby", "name": "Zophie"}, {"des": "fluffy", "name": "Pooka"}]
# 读取一下试试
>>> import mycats
>>> mycats.cats
[{'desc': 'chubby', 'name': 'Zophie'}, {'des': 'fluffy', 'name': 'Pooka'}]
# yes