python-文件操作

系列文章;

python编程基础(精讲)专栏

文件

文件对象是python代码调用电脑上存放的外部文件的主要接口。它们能被用于读取和写入文本记录、音频片段、Excel文档、保存邮件以及任何你保存在电脑上的东西。

创建一个文本输出文件;

f = open('data.txt','w')
f.write('hello word\n')
f.close()

这样就在当前文件夹下创建了一个文件,并向它写入文本。

为了读取刚才所写入的内容,则可以重新以 ’ r '处理模式打开文件,然后将文件的内容读至一个字符串,并显示它。

f = open('data.txt','r')
text = f.read()
print(text)
print(text.split())
输出:
hello word
['hello', 'word']

操作文件最核心的函数是open()函数,此函数需要两个参数:file,name, mode。filename对应你要操作的文件名,mode对应你要对文件进行的操作,不同mode对应的具体意义。

  • ’ r '表示以输入模式打开文件(默认值)
  • ’ w '表示以输出模式生成并打开文件(覆盖写入)
  • ’ a '表示在文件末尾追加内容并打开文件(追加写入)
操作解释
output = open(r’C:\spam’, ‘w’)创建输出文件('w’代表写入)
input = open(‘file’, ‘r’)创建输入文件('r’代表读入)
input = open(‘file’)与上一行相同’r’是默认值
aString = input.read( )把整行文件读进一个字符串
aString = input.read(N)读取接下来的N个字符到一个字符串
String = input.readline( )读取下一行(包含\n换行符)
aList = input.readlines( )读取文件到一个字符串列表
output.write(aString)把字符串写入文件
output.writelines(aList)把列表内所有字符串写入文件
output.close( )手动关闭
output.flush( )把输出缓冲区刷入硬盘中,但不关闭文件
anyFile.seek(N)把文件位置偏移到偏移量N处
for line in open(‘file’): use line文件迭代器逐行读取
open(‘f.txt’, encoding=‘utf-8’)unicode字符串
open(‘f.bin’, ‘rb’)bytes字符串 (二进制文件对象)

使用文件

>>> myfile = open(r'/Users/abel/Desktop/myfile.txt','w')
>>> myfile.write('Do nothing by halves.')
21
>>> myfile.write('A fair face may hide a foul heart. \n')
36
>>> myfile.close()
>>> myfile = open(r'/Users/abel/Desktop/myfile.txt','a')
>>> myfile.write('Rome was not built in a day.\n')
29
myfile.close()
>>> myfile = open(r'/Users/abel/Desktop/myfile.txt')
>>> myfile.readline()
'Do nothing by halves.A fair face may hide a foul heart. \n'
>>> myfile.readline()
'Rome was not built in a day.\n'
>>> open(r'/Users/abel/Desktop/myfile.txt').read()
'Do nothing by halves.A fair face may hide a foul heart. \nRome was not built in a day.\n'
for line in open(r'/Users/abel/Desktop/myfile.txt'):
	print(line, end='')
Do nothing by halves.A fair fac

这里,我们文件中所存的都是字符串格式的内容。如果是python中的对象,我们需要进行转换。

>>> x, y, z = 43, 44, 45
>>> S = 'spam'
>>> D = {'a':1, 'b':2}
>>> L = [1,2,3]
>>> f = open(r'/Users/abel/Desktop/datafile.txt', 'w')
>>> f.write(S + '\n')
>>> f.write('%s,%s,%s\n' % (x,y,z))
>>> f.write(str(L) + '$' + str(D) + '\n')
>>> f.close()
>>> chars = open(r'/Users/abel/Desktop/datafile.txt').read()
>>> chars
"spam\n43,44,45\n[1, 2, 3]${'a': 1, 'b': 2}\n"
>>> print(chars)
spam
43,44,45
[1, 2, 3]${'a': 1, 'b': 2}
>>> f = open(r'/Users/abel/Desktop/datafile.txt')
>>> line = f.readline()
>>> line
'spam\n'
>>> line = f.readline()
>>> line
'43,44,45\n'
>>> line = f.readline()
>>> line
"[1, 2, 3]${'a': 1, 'b': 2}\n"
>>> parts = line.split('$')
>>> parts
['[1, 2, 3]', "{'a': 1, 'b': 2}\n"]
>>> eval(parts[0])
[1, 2, 3]
>>> objects = [eval(p) for p in parts]
>>> objects
[[1, 2, 3], {'a': 1, 'b': 2}]

转换文件第三行所存储的列表和字典,我们运行了内置函数eval,eval能把字符串当作可执行程序代码。eval可以把字符串转换成对象。

当然也可以使用python中的pickle模块。

JSON格式

在python对象和文件中,JSON数据字符串之间的相互转换是非常直接的。在被存入文件之前,数据是简单的python对象;当从文件中读取对象时,json模块将它们从JSON表示重建成对象。

>>> name = dict(first='Bob', last='Smith')
>>> rec = dict(name=name, job=['dev', 'mgr'], age=40)
>>> rec
{'name': {'first': 'Bob', 'last': 'Smith'}, 'job': ['dev', 'mgr'], 'age': 40}
>>> import json
>>> json.dumps(rec)
'{"name": {"first": "Bob", "last": "Smith"}, "job": ["dev", "mgr"], "age": 40}'
>>> fp = open(r'/Users/abel/Desktop/datafile.json','w')
>>> json.dump(rec,fp)
>>> fp.close()
>>> f = open(r'/Users/abel/Desktop/datafile.json')
>>> content = json.load(f)
>>> print(content)
{'name': {'first': 'Bob', 'last': 'Smith'}, 'job': ['dev', 'mgr'], 'age': 40}

文件上下文管理器(扩展)

python中,我们可以把文件处理代码包装到一个逻辑层中,以确保在退出后一定会自动关闭文件(同时可以满足将其输出缓冲区内容写入磁盘),而不是依赖于垃圾回收时的自动关闭。

with open(r'C:\code\data.txt') as f:
    content = f.read()

类似于;

f = open(r'C:\code\data.txt')
try:
    '''use file'''
    print(f)
finally:
    f.close()
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

他是只猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值