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 <module>
    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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值