读写文件 1

本文详细介绍了Python中如何使用 进行换行, 实现tab对齐,以及如何利用open函数读写文件。通过实例展示了不同转义字符在文本格式化中的应用,并演示了如何创建和写入文本到指定文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

\n 换行命令 

定义 text 为字符串, 并查看使用 \n 和不适用 \n 的区别:

使用 \t 能够达到 tab 对齐的效果:

>>> text = 'test hello hahhahaha secondl line. third'
>>> print(text)
test hello hahhahaha secondl line. third
>>> text = 'test hello hahhahaha\n secondl line. \nthird'
>>> print(text)
test hello hahhahaha
 secondl line. 
third
>>> text = '\ttest hello hahhahaha\n secondl line. \n\tthird'
>>> print(text)
	test hello hahhahaha
 secondl line. 
	third
>>> 

open 读文件方式 

使用 open 能够打开一个文件, open 的第一个参数为文件名和路径 ‘my file.txt’, 第二个参数为将要以什么方式打开它, 比如 w 为可写方式. 如果计算机没有找到 ‘my file.txt’ 这个文件, w 方式能够创建一个新的文件, 并命名为 my file.txt


>>> # -*- coding:UTF-8 -*-
... my_file = open('test.txt','w') #用法: open('文件名','形式'), 其中形式有'w':write;'r':read.
>>> text = 'Python 2.7.16 |Anaconda, Inc.'
>>> my_file.write(text)
>>> my_file.close()
>>> 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值