python-文件 *** 作

python-文件 *** 作,第1张

python-文件 *** 作

系列文章;

python编程基础(精讲)专栏

文章目录
  • 文件
  • 使用文件
  • JSON格式
  • 文件上下文管理器(扩展)

文件

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

创建一个文本输出文件;

f = open('data.txt','w')
f.write('hello wordn')
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,%sn' % (x,y,z))
>>> f.write(str(L) + '$' + str(D) + 'n')
>>> f.close()
>>> chars = open(r'/Users/abel/Desktop/datafile.txt').read()
>>> chars
"spamn43,44,45n[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
'spamn'
>>> line = f.readline()
>>> line
'43,44,45n'
>>> 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:codedata.txt') as f:
    content = f.read()

类似于;

f = open(r'C:codedata.txt')
try:
    '''use file'''
    print(f)
finally:
    f.close()

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5491409.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存