Python文件的创建与写入

本文详细介绍了Python中如何使用内置函数`open`创建和写入文件,包括文件操作模式、文件对象的方法,并通过实例展示了文件的写入保存过程。记得在完成操作后调用`close`方法确保数据保存。
摘要由CSDN通过智能技术生成

目录

  • 利用内置函数open获取文件对象
  • 文件操作的模式之写入
  • 文件对象的操作方法之写入保存

利用内置函数open获取文件对象

  • 功能:
    • 生成文件对象,进行创建,读写操作
  • 用法:
    • open(path,mode)
  • 参数说明∶
    • path:文件路径
    • mode :操作模式
  • 返回值:
    • 文件对象
  • 举例:
    • f = open('d://a.txt' , ‘w')

文件操作的模式之写入

在这里插入图片描述

文件对象的操作方法

在这里插入图片描述

操作完成后,必须使用close方法!

In [1]: import os

In [2]: current_path = os.getcwd()

In [3]: current_path
Out[3]: 'D:\\My_Files\\Python Project\\pythonlean\\python_package'

In [4]: f = open(current_path + '/' + 'a.txt', 'w', encoding='utf-8')

In [5]: f.write('hello 小明')
Out[5]: 8

In [6]: f.close()

In [7]: path = os.path.join(current_path, 'a.txt')

In [8]: path
Out[8]: 'D:\\My_Files\\Python Project\\pythonlean\\python_package\\a.txt'

In [9]: f = open(path, 'w', encoding='utf=8')

In [10]: f.write('你好 小华')
Out[10]: 5

In [11]: f.close()

In [12]: f = open(path, 'w+', encoding='utf=8')

In [14]: f.write('你好 insane')
Out[14]: 9

In [15]: f.close()

In [16]: f = open(path, 'w', encoding='utf=8')

In [17]: f.write('hahaha')
Out[17]: 6

In [18]: f.read()
-------------------
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值