栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python文件操作

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python文件操作

文件和异常 1.1 读取整个文件

已存在的file文件夹下新建test.txt文件

1
22
333
with open('test.txt') as file_object:
	contents = file_object.read()
	print(contents)

函数open()接受一个参数:要打开的文件名称,Python默认在当前执行的程序所在的目录中查找指定的文件;函数open()返回一个文件对象,在这里将这个对象存储为file_object这个变量中。

关键字with在不使用文件后自动将其关闭,在这个文件中我们调用了open()但没有调用close();使用这种方式的好处就是可以让Python自己去确定,你只管打开文件,当你使用完以后Python会自动将其关闭。

有了文件对象后,我们使用read()读取这个文件的全部内容,并将其存储在变量contents中,这样通过打印,就可以将其文件的全部内容显示出来。

1.2 文件路径

相对路径
运行程序在file文件夹中,可以使用相对路径来访问文件。

with open('file/test.txt') as file_object:
	contents = file_object.read()
	print(contents)

绝对路径
文件存储在计算机中的准确位置

with open('/Users/huangxiongjin/documents/file/test.txt') as file_object:
	contents = file_object.read()
	print(contents)
1.3 逐行读取
with open('test.txt') as file_object:
	for line in file_object:
		print(line)
with open('test.txt') as file_object:
	for line in file_object.readlines():
		print(line)

消除右边空字符串、换行

with open('test.txt') as file_object:
	for line in file_object:
		print(line.rstrip())
1.4 写入文件
类型说明注意
r只读方式打开文件必须存在
r+只读方式打开文件必须存在
w只写方式打开文件不存在创建文件,文件存在则清空文件内容
w+读写方式打开文件不存在创建文件,文件存在则清空文件内容
a追加方式打开文件不存在创建文件
a+读写和追加方式打开文件不存在创建文件
1.5 存储数据

使用json存储数据

写入文件

imoort json

data_str = 'hello, world'
with open('test.txt', 'w') file_object:
	json.dump(data_str, file_object)

读取文件

imoort json

with open('test.txt') file_object:
	data = json.load(file_object)
print(data)
1.6 处理文件异常
# 读取一个不存在的文件
filename = 'alice.txt' 
with open(filename) as f_obj: 
	contents = f_obj.read()


Traceback (most recent call last):
  File "alice.py", line 3, in 
    with open(filename) as f_obj:
FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt'

使用try-except处理异常

try:
    with open(filename) as f_obj:
		contents = f_obj.read()
except FileNotFoundError:
    msg = "Sorry, the file " + filename + " does not exist." 
    print(msg)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/769820.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号